Hi i am a newbie in c++ and was doing some basic exercise. my code takes user input and feeds them in an array. Now i am using getline() to get the input string. my code is as follows:
cin.getline(cb[0].name, 200).get(); // Cadburry
cin.getline(cb[1].name, 200).get(); // Snickers
cin.getline(cb[2].name, 200); // Milky Bar
But when i output the strings, the first getline() seems to be fine but the other two are omitting the first letter of the string. So the output in this case is :
Cadburry
nickers
ilky Bar
can anyone please tell me why is it so?
The get() calls are consuming the S and the M, remove those and it will work. getline() already consumes the \n
Related
I was learning how to read strings with getline function.
I know that getline function read string as far as we don't hit enter or the size value in the getline parameter go cross. As far as I tried getline function to read one line of string I had not faced any problem.
But when I was trying to read two line of string one after another in two different char array i got the output that was not expected to me.
To understand my question follow bellow lines
#include <iostream>
using namespace std;
int main()
{
char line1[10];
char line2[10];
cin.getline(line1,7);
cin.getline(line2,7);
cout << "\nline1 =" << line1 <<endl;
cout << "line2 =" << line2 <<endl;
}
When I ran the above program it ask me for input then I gave orange as first input and hit the enter button.
Next it ask me to give the second input .then i gave banana and hit the enter button .in this case it produce the result i expected .But if enter oranges for the first input it does not wait for me to enter the second input.
As a result line1 store orange but line2 remains blank.
Now my question is that there is no wrong with line1 storing orange. But I don't understand why the line2 remains blank should not it contain the data that remains after line1 take input I mean should not line2 contain s as value.
Because orange is a 6 digit word so getline will stores the first six digit after then a null character will be added as I set the size of geline 7.
Then other remaing data will be assigend in the next call of getline function.So should not s stored in line2 as after s a new_line character is read for the first time.
Why will be line2 remain blank and why the screen doesn't stop for taking input after giving the first input?
std::istream::getline is being overloaded with data.
According to cppreference,
Behaves as UnformattedInputFunction. After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):
end of file condition occurs in the input sequence (in which case setstate(eofbit) is executed)
the next available character c is the delimiter, as determined by Traits::eq(c, delim). The delimiter is extracted (unlike basic_istream::get()) and counted towards gcount(), but is not stored.
count-1 characters have been extracted (in which case setstate(failbit) is executed).
Emphasis mine.
cin.getline(line1,7);
// ^ This is count
can read only 6 characters with the 7th reserved for the null terminator. "oranges" is seven characters, and this places cin in a non-readable error state that must be cleared before reading can be continued. Reading of the second line
cin.getline(line2,7);
instantly fails and no data is read.
The obvious solution is
cin.getline(line1, sizeof(line1));
to take advantage of the whole array. But...
Any IO transaction should be tested for success, so
if (cin.getline(line1, sizeof(line1)))
{
// continue gathering
}
else
{
// handle error
}
is a better option.
Better still would be to use std::getline and std::string to almost eliminate the size constraints.
I am in a bind right now and the most frustrating thing about this is that I know what the problem is but, I cannot fix it :(...
My goal is to ultimately use getline to read lines of strings from redirected input (from a text file) and keep going until EOF is reached.
Example text file (contents):
Hello World!
Good Bye.
My source code(only includes the section where it will not work):
while (!(getline(std::cin, s_array)).eof()){ // it won't read second line
//do some awesome stuff to the first line read!
}
As far as I know, getline reads everything upto the newline and stops so how do we get it to keep reading because it always stops at Hello World!.
Use while (getline(std::cin, s_array)) { } instead.
std::getline() returns istream&, and istream::operator void*() makes it evaluated as false whenever any error flag is set.
You should definitely read Joseph Mansfield's blog post titled "Don't condition input on eof()" which describes this pitfall in details and provides a well justified guideline.
Could seem an old question, but the problem here isn't the use of TWO cin.get(), but of more than two! if I write (in DEV C++)
I get just one input request (s) and then end program. Now, I expected having at least two request of cin, because I expected:
char s[50];
char t[100];
char r[100];
char f[100];
cin.get(s,49);
cin.get(t,99);
cin.get(r,99);
cin.get(f,99);
I expeted at least 2 input request, because:
first cin: buffer empty,I insert the string s and \n
second cin: I have in buffer \n still, then t=\n without input request
third cin: buffer empty, I insert the string r and \n
fourth cin: I have in buffer \n still, then f=\n without input request
But I have just the input request for s string!
why have I just one input request?the buffer didn't clean with second cin.get, letting third cin.get work properly? Thanks
t does NOT equal '\n'. It's empty. .get(char*,int) will never remove the '\n' from the buffer.
Worse, the attempt to read to t will set cin to a fail state since nothing could be read, which will cause all subsequent reads of any sort from cin to fail immediately without even trying until you .clear() the fail state.
This is surprising behavior, but you seem to have already guessed at most of it as per your last sentence in the question, so, Good Job! You're learning!
http://en.cppreference.com/w/cpp/io/basic_istream/get
Im using scanf because we must use it.
the problem is the following :
(thats just an example of the problem):
int main() {
char ch [10]={0};
scanf("%s",ch);
printf("%s",ch);
}
if i run the program and enter for example : word^Z
when ^Z is EOF.
the program stays in place, stuck in the scanf, althogh i did type word then ctrl+z then Enter. but somehow it stays in the scanf, its the same thing with redirection, like its not a problem with ctr+z or anything.
i hope that i can get some help
thanks in advance,
totally apprecaite it :)
scanf uses whitespace as a delimiter to store the read data into various fields. From the command line, entering ControlZ, then Enter only puts the EOF character into the input stream and scanf() continues waiting for whitespace. If you hit Enter again, scanf will receive the whitespace character, and everything including the EOF will be stored into the ch array.
Here's a sample run. The first line is the input, and the second line is the output.
Hello^Z
Hello→
I mam trying to complete a college assignment in C++ and am having trouble with what should be a very basic operation. I am trying to read a string of characters from the keyboard. This is the relevant code:
string t;
cout << endl << "Enter title to search for: ";
getline(cin, t, '\n');
I understand, that the last line is supposed to read the input buffer (cin , in this instance) and store the character in the 't' string until it reaches a new line character and then continue the program flow.
However, when I run my code in XCode, it just sort of jumps over the getline function and treats 't' as an empty string.
What's going on? I tried using cin >> t but that just read characters forever - Why cant I get this to behave?
The reason that the input operation apparently is skipped, is most probably (that means, ignoring possible peculiarities of a bugsy XCode IDE) that you have performed some input earlier and left a newline in the input buffer.
To fix that, make sure that you have emptied the input buffer after each input operation that logically should consume a line of input.
One easy way is to always use getline into a string, and then use e.g. an istringstream if you want to convert a number specification to number type.
Cheers & hth.,
From the docs page it looks like you want
cin.getline(t,256,'\n');
or something similar.
This sounds like an issue with the way Xcode is running your program. Try running your program directly from the terminal, and see if this is sufficient to fix your issue.