**EDIT: I got it to work by changing the 'inStream >> next' to 'inStream >> skipws >> next'. In one of my earlier functions (to pull the last and first name) I had toggled noskipws. Apparently that toggle lasts between functions?
I have a program that is part of an assignment that is supposed to read a text file that is set up in the format of: "lastname firstname 1 2 3 4 5 6 7 8 9 10" (where each of the 10 numbers are integer scores).
I am able to read in the lastname and firstname fine, but when I go to start reading in the numbers, I am only able to read in the first one and then all the rest get set to 0.
Below is the function that is supposed to read the scores in. inStream has already had the lastname and firstname taken off. The textfile I am using has one line:
Tosis Halley 85 23 10 95 43 12 59 43 20 77
When run the program and print out the student.score values from 0 to 9, the first one displays correctly as '85' but all the reset show as '0'. Thoughts?
void GetScores (ifstream& inStream, record& student)
{
int score[10] = {-1, -1, -1, -1 ,-1 ,-1 ,-1 ,-1 ,-1 ,-1};
int next;
int counter = 0;
string test;
for (int i = 0; i < 10; i++)
{
inStream >> next;
student.score[i] = next;
}
}
Assuming the input is indeed all numbers, the function should actually work. However, you should always verify that inputs were indeed read correctly:
for (int i = 0; i != 10 && inStream >> next; ++i) {
student.score[i] = next;
}
if (!inStream) {
std::cout << "an input error occured\n";
}
Related
while(true) {
infile >> studentCode >> test1 >> test2 >> lab >> finalExam;
finalG = finalGrade(test1, test2, lab, finalExam);
gradeSum = gradeSum + finalG;
letterG = letterGrade(finalG);
gradePrinter(); // Prints grades to outfile.
if (infile.eof())
break;
}
In my while loop, the variable finalG does not add to gradeSum at the end of every loop. (gradeSum is initialized to 0 before the while loop). Instead, the value of gradeSum stays at zero and just adds whatever the last number the function finalGrade(test1, test2, lab, finalExam) outputs. For example, if the following numbers are outputted by function:
10
15
30
35
40
The gradeSum will return 40 + 0, which just gives me 40 rather than the sum of the numbers. How can I fix this?
Problem
Your use of the while loop is faulty. You end up processing the grades one more time than is valid.
Let's say you have two lines in your file:
101 18 20 15 48
102 19 20 14 50
After the second line is read, infile.eof() is false. Hence, you continue reading. Reading does not succeed. Yet you process those numbers. You will probably end up processing the last line twice.
A solution
Simplify the while loop by using:
while ( infile >> studentCode >> test1 >> test2 >> lab >> finalExam )
{
finalG = finalGrade(test1, test2, lab, finalExam);
gradeSum = gradeSum + finalG;
letterG = letterGrade(finalG);
gradePrinter();
}
Disclaimer: This won't fix other logic errors in your code.
I was trying to write a code in C++ in Windows using MinGW compiler, my code counts and prints the number of consecutive times a number occurs in a given set of input. The code is as follows:
#include <iostream>
int main()
{
int c_val = 0,val = 0,cnt = 1;
std::cin>>c_val;
while(std::cin>>val){
if(val==c_val)
cnt++;
else{
std::cout<<c_val<<" occurs "<<cnt<< " times"<<std::endl;
c_val = val;
cnt = 1;
}
}
std::cout<<val<<" occurs "<<cnt<<" times";
}
INPUT: 42 42 42 12 13 13 ^Z (press Enter)
OUTPUT:
42 occurs 3 times
12 occurs 1 times
0 occurs 2 times
But if I press Enter before ^Z then it looks like:
INPUT: 42 42 42 12 13 13 (press Enter) ^Z (press Enter)
OUTPUT:
42 occurs 3 times
12 occurs 1 times
13 occurs 2 times
I want to know why the variable val in my code stores 13, when I use ^Z key after pressing my return key and why does it store 0 if I give the ^Z key along with my input.
Here is what happens. I observed this using MinGW-w64 4.9.2. The behaviour was the same whether running the executable in a Windows console, or under Cygwin (but not using cygwin-mingw).
Pressing ^Z at the beginning of a line sets the end-of-file condition
Pressing ^Z anywhere else actually sends ASCII 26 character to the stream
I also observed:
cin >> val sets val to 0 if it fails due to the input not containing a number.
cin >> val leaves val unchanged if input fails due to end-of-file.
According to this thread that is the correct behaviour specified by C++11.
So your results can be explained. When you input 42 42 42 12 13 13^Z, it is the same as if you had written 42 42 42 12 13 13x. The first six numbers are read, and then when x is encoutered, cin >> val fails and sets val to 0.
But when you press Enter and then ^Z, it is as if you were reading from a file and you reached the end of the file. cin >> val leaves val unchanged and it is still holding the value that it had after the last successful cin >> val.
If you make the change suggested by Gautam Jha suggested then you will get 13 in both cases. This is because he effectively reads into a temporary int, and then only stores the temporary int into the real val if the read succeeded, thereby avoiding the behaviour where a failed read sets val to 0.
This is probably the desired behaviour although you might also want to check cnt > 0 to avoid a weird output in the case of totally empty input.
See the difference
#include <iostream>
int main()
{
int c_val = 0,val = 0,cnt = 1;
std::cin>>c_val;
int curr_val = 0;
while(std::cin>>val){ // in case of no value cin will set val =0
curr_val = val;
if(curr_val == c_val)
cnt++;
else{
std::cout<<c_val<<" occurs "<<cnt<< " times"<<std::endl;
c_val = curr_val;
cnt = 1;
}
}
std::cout<<curr_val<<" occurs "<<cnt<<" times";
}
so I'm trying to write a program that would take an input character between 0 and 127 and then output a string of numbers in the following form:
- If I input a 0, the output should be a 0
- If I input a 5, the output should be 012345
- If I input a 9, the output should be 0123456789
- If I input a 14, the output should be 012345678901234
- If I input a 27, the output should be 0123456789012345678901234567
So, I'm looking for increments of 10 characters from 0 to 9 at most and then repeat the sequence until the last number is reached. So in 27, there's actually 28 characters output due to the first 0, but the last one is still a 7.
I know I want to use for loops, but I'm having a bit of a trouble figuring out how to make this happen. I can probably use the the ASCII 48 through 57 for the output, but my problem is how I make the input work... should I static cast it to an integer and then work with that? I'm kind of hitting a wall here.
Try the following:
#include <iostream>
int main() {
char input;
std::cin >> input;
if (input >= 0 && input <= 127) {
for (int i = 0; i <= n; i++) std::cout << i % 10;
}
}
int lineInputs = 0;
cin >> lineInputs;
int whatever = 0;
char* myArray = new char[arrayElements*lineInputs];
int j =0;
for(int i = 0; i < lineInputs; i++)
{
cin >> whatever;
for(j; j<total; j+=39)
{
for(int nom=0; j<arrayElements; nom++)
{
cin >> myArray[j];
}
}
}
In my forloop say i have lineInputs = 4 and total = 156
Meaning 4 times we do this, we want to insert 156 chars into my array. But we want to make it so that every 40 characters we continue entering the array.
Bsically we need to insert this input into the array but i feel like my forloops are messed up. This will be the input
4
1
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
2
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
3
HHTTTHHTTTHTHHTHHTTHTTTHHHTHTTHTTHTTTHTH
4
HTHTHHHTHHHTHTHHHHTTTHTTTTTHHTTTTHTHHHHT
The first line 4 meaning 4 of these 40 character lines. And the number above the character lines just signifying line 1 2 3 4 ect.
How can i attempt this right?
So the array would basically look like this.
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTHHTTTHHTTTHTHHTHHTTHTTTHHHTHTTHTTHTTTHTHHTHTHHHTHHHTHTHHHHTTTHTTTTTHHTTTTHTHHHHT
You are making the same fundamental mistake you made in your other question, which is to fail to treat the input array correctly. You are repeatedly reading into the first 40 characters of myArray. What you need to do is read the first line into the first 40 characters, the second line into characters 40 to 79, etc.
Better yet, make it a two dimensional array so that you don't have to muck around with computing the indices.
Even better, make it an array of std::string rather than an array of char.
I need to get very basic input from an external file in C++. I tried searching the internet a few times but nothing really applied to what I need. This would be a .txt file that the input it coming from, and it would be filled with lines like this:
131
241
371
481
I have code already to manually get this input, and it looks like this:
using namespace std;
//Gets the initial values from the user.
int control=0;
while (rowb!=0){
cout << "Row: ";
cin >> rowb;
cout << "Column: ";
cin >> columnb;
cout << "Number: ";
cin >> numb;
row[control]=rowb-1;
column[control]=columnb-1;
num[control]=numb;
control++;
}
This is part of a program that solves sudoko boards. The inputed numbers are the initial values that a sudoko board holds, and the user is inputing the row, column, and number that comes from a board.
What I need is to be able to create a .txt file with these numbers stored in rows so that I do not have to enter so many numbers. I have very little idea how to go about doing this. Mainly I'll only be using the txt file for testing my program as I move along with adding more code to it. It takes 150+ entered numbers within my program just to get a single board, and it takes a lot of time. Any accidentally wrong entered value is also a huge problem as I have to start again. So how would I get C++ to read a text file and use those numbers as input?
Aside from the other suggestions, you can simply redirect a file to standard input, like so (where $ is the command prompt):
$ myprogram < mytextfile.txt
That will run myprogram just as normal but take input from mytextfile.txt as if you had typed it in. No need to adjust your own program at all.
(This works on both Unix/Linux systems and on Windows.)
You can open a file for input with std::ifstream from the header <fstream>, then read from it as you would from std::cin.
int main()
{
std::ifstream input("somefile.txt");
int a;
input >> a; // reads a number from somefile.txt
}
Obviously, you can use >> in a loop to read multiple numbers.
Create an std::ifstream object, and read from it just like you would from std::cin. At least if I understand what you're trying to do, the 131 as the first input is really intended to be three separate numbers (1, 3, and 1). If so, it's probably easiest to change your input file a bit to put a space between each:
1 3 1
2 4 1
3 7 1
4 8 1
Personally, I would start with a different format of the file: enter a value for each cell. That is, each row in the input file would represent a row in the sudoko board. Empty fields would use a space character. The immediate advantage is that the input actually pretty much looks like the sudoko board. Also, you would enter at most 90 characters: 9 characters for the board and a newline for each line:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
int main(int ac, char* av[])
{
std::ifstream in(ac == 1? "sudoko.init": av[1]);
char board[9][9];
for (int i(0); i != 9; ++i)
{
in.read(board[i], 9).ignore();
}
if (!in)
{
std::cout << "failed to read the initial board\n";
}
else
{
typedef std::ostream_iterator<char> iterator;
std::fill_n(iterator(std::cout << "board:\n\n+", "+"), 9, '=');
for (int i(0); i != 9; ++i)
{
std::copy(board[i] + 0, board[i] + 9, iterator(std::cout << "\n|", "|"));
std::fill_n(iterator(std::cout << "\n+", "+"), 9, (i + 1) % 3? '-': '=');
}
std::cout << "\n";
}
}
This would take input like this:
4 5 3 8
71 3
16 7
6 4 7
6 8
1 9 5
6 42
5 94
4 7 9 3
Note that each of these lines uses 9 characters. You might want to use something more visible like ..