This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 5 years ago.
Giving input as:
Input:
3
1 2 3
4 5 6 7
8 9 10 11 12
Expected Output:
1 2 3
4 5 6 7
8 9 10 11 12
But it is giving the Output-
1 2 3
4 5 6 7
Why it is not giving the last line ? Is there any mistake in my code?
#include <iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{ string str;
getline(cin,str,'\n');
cout<<str<<endl;
}
return 0;
}
It's because cin>>t doesn't read the end-of-line. The first time you call getline you're getting an empty string.
I can think of a couple of ways of getting around this offhand. First is to skip over the whitespace at the end of the first number, since a newline counts as whitespace. Unfortunately this will also skip whitespace at the beginning of the next line.
cin >> t >> std::ws;
The other way is to use getline to skip past the end of the line and ignore the string you get back.
cin >> t;
getline(cin, str, '\n');
Related
This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 6 months ago.
I'm new to c++. Currently I'm learning how to read and write to a file. I've created a file "nb.txt" with content like this:
1 2 3 4 5 6 7
2 3 4 5 6 7 9
I'm using a simple program to read this file, looping until reached EOF.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream in("nb.txt");
while (in) {
int current;
in >> current;
cout << current << " ";
}
}
What I'm expecting is the program will output all of the values.
But what I'm really getting is this:
1 2 3 4 5 6 7 2 3 4 5 6 7 9 9
There's a multiple "9" in the output. I don't understand what's happening! Is it because of the while loop?
Can anyone help me to figure out why there is another "9"? Thanks!
The problem is that after you read the last value(which is 9 in this case) in is not yet set to end of file. So the program enters the while loop one more time, then reads in(which now sets it to end of file) and no changes are made to the variable current and it is printed with its current value(which is 9).
To solve this problem, you can do the following:
int main() {
ifstream in("nb.txt");
int current=0;
while (in >> current) { //note the in >> curent
cout << current << " ";
}
}
The output of the above program can be seen here:
1 2 3 4 5 6 7 2 3 4 5 6 7 9
This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 7 years ago.
I have a file like this:
4 88 101
1 22 100
6 41 151
I have 3 arrays and i want to put the first values(4, 1, 6) to my first array, the second values(88, 22, 41) to my second array etc.
So how can I split each line by space??
I have already read the file but I cannot fill my arrays with these values.
If you know the exact number of items per line of data from the file, you can open it with an ifstream and do:
int firstNum, secondNum, thirdNum;
while (inFile >> firstNum >> secondNum >> thirdNum)
{
//do something
}
I have this code :
int obj;
while ( std::cin >> obj )
{
std::cout << obj << std::endl ;
int temp = obj ;
++ temp;
std::cout << temp << std::endl ;
}
When I give proper integer inputs, I understand the output.
eg. If I get 12 as input, I see something like this on console :
12
12
13
But, if I give some integers with white spaces as input, I can't seem to understand the output.
eg. If I give 12 12 12 12 as input, I see this on console :
12 12 12 12
12
13
12
13
12
13
12
13
Can someone please explain ?
The first example includes your input.
input
12
output
12
13
The second example is exactly this, multiplied 4 times, for each of the 4 numbers received as input. The seperator is "whitespace" - spaces, new lines or tabs. It is not a "non integer", but rather "four integers":
The input:
12 12 12 12
is equivalent to
12
12
12
12
output:
12
13
12
13
12
13
12
13
The loop reads whatever the input is, only after you hit "enter". So in the first case, it reads one value 12, prints 12 then 13 for the updated value in temp, then goes back waiting for you to type more numbers.
In the second case, it reads 12, prints 12 & 13, then goes back, reads another 12, prints 12 & 13, and so on another 2 times. Then goes back waiting for your to type more data.
Note that whitespace is a proper separator for your input. If you want it to go wrong, try typing 12a, in which case it will print 12 & 13 forever (well, until you get bored and stop it), since it will "stop reading" at the 'a' without updating obj - and because nothing in the loop clears out the a, it keeps going.
When you add the space, it takes them as separate values. And run the while loop for each of them.
int obj;
cin >> obj;
cin reads valid integer data from your input until it finds a character that does not belong to an integer, or there is no more data. In your first example, cin hits the end of your input and returns the number. In your second example, cin reads the input from the string "12 12 12 12", extracts the first integer from your input stream and writes it to obj. In the next run of your while loop, cin is confronted with the string "12 12 12" (since it has extracted/removed the first number from your input stream) and the story continues until there is no more input to read from.
I have a text file containing names and numbers. The name or the string contains 15 chars and I need to put it to the string. I'm working with structures.
struct grybautojas{
string vardas;
int barav, raudon, lep, diena;
}gryb[100];
After that, there are simple calculations which is done right, the problem is, it only reads everything once. After taking a first "box" of information, it just stops. Everything else in the result file is either blank as a string or 0 as an integer.
Here's my input function:
void ivedimas(){
char eil[16];
int b,r,l;
inFile >> n;
inFile.ignore();
for(int i=0;i<n;i++){
inFile.get(eil,15);
gryb[i].vardas=eil;
inFile >> gryb[i].diena;
gryb[i].barav=0, gryb[i].raudon=0, gryb[i].lep=0;
for(int m=0;m<gryb[i].diena;m++){
inFile >> b >> r >> l;
gryb[i].barav+=b, gryb[i].raudon+=r, gryb[i].lep+=l;
}
inFile.ignore();
}
inFile.close();
}
And here's the file containing data:
4
Petras 3
5 13 8
4 0 5
16 1 0
Algis 1
9 6 13
Jurgis 4
4 14 2
4 4 15
16 15 251
1 2 3
Rita 2
6 65 4
4 4 13
What's the problem?
inFile.get(eil,15);
Rita 2
Petras 3
00000000011111
12345678901234
I don't count 15, I count 14. Also, some of your lines seem to have a space at the end. You should rewrite your input logic to be much more robust. Read lines and parse them.
This line:
inFile.get(eil,15);
is reading the number that follows the name.
When you try to read the number (3 in your example), you get the next one (5) instead.
I am using scanf to take input for a graph. The input is as follows :
8
1 2
3 3 5 6
2 4 7
2 3 8
2 1 5
1 7
2 6 4
0
The first integer (8) is the number of vertices, followed by 8 line. The first integer in each is the number of outgoing edges from vertex 1 in the first line, vertex 2 in the second line and so on.
The function i have written is as follows :
void getInput() {
//init();
int numVertex; int numTest;
scanf("%d", &numVertex);
for(int i =1 ; i <= numVertex;i++) {
int ver,nC; vector<int> vList;
//fscanf(file,"%d", &ver);
scanf("%d", &nC);
for(int j=0;j<nC;j++) {
int temp ;
scanf("%d", &temp);
vList.push_back(temp);
}
props pr = {-1,-1 , vList};
graph.insert(make_pair(i, pr) );
}
}
However, the output for the last line of my input becomes weird and it basically repeats the last digit of its previous line multiple times. For the above input , the output I am getting :
1 : 2
2 : 3 5 6
3 : 4 7
4 : 3 8
5 : 1 5
6 : 7
7 : 6 4
8 : 4 4 // this is where it should give nothing
Can anyone tell me whats going wrong here? The exact same sequences of conversions, when I convert to taking input through file gives me the right output.
Can someone please point me to any error?
Do it like this:
if (scanf("%d", &nC) != EOF) {
for(int j=0;j<nC;j++) {
int temp ;
scanf("%d", &temp);
vList.push_back(temp);
}
props pr = {-1,-1 , vList};
graph.insert(make_pair(i, pr) );
}
This will check if the read was successful. The repetition of the last line of input is a well known issue and occurs because the last read attempt fails (because end of file has reached) and scanf returns the same result as its previous call.
What is props?
Whatever it is, doing C-style struct initialization on something containing an std::vector is asking for trouble - the results are undefined and almost surely not what you want.
Your input code seems OK though, despite lack of error-checking as noted in another answer.