In: Computer Science
Infile and getline - how can I change this code to get the whole line from a text file? Right now it only gets the first word each time it reads. NUMBER can be any integer. This code gets strings that are in multiple lines from a text file. Some words are separated by whitespace and that makes the input wrong. It only works if there is only one word.
infile >> arrayOne[dive] >> arrayTwo[dive];
while (infile && dive< NUMBER)
{
dive++;
infile >> arrayOne[dive] >> arrayTwo[dive];
}
infile >> arrayOne[dive] >> arrayTwo[dive];
}
In C++, if we need to read few sentences from a stream, the generally preferred way is to use getline() function. It can read till it encounters newline or sees a delimiter provided by user.
Here is a sample program in c++ that reads four sentences and displays them with ” : newline” at the end.
using
namespace
std;
int
main()
{
string
str;
int
t = 4;
while
(t--)
{
//
Read a line from standard input in str
getline(cin,
str);
cout
<< str <<
" : newline"
<< endl;
}
return
0;
}
Getline In C++
While using C++, std::cin does not support accepting multiple lines in one go, to do this we have some in-built functions like getline. To accept a string or a line of input stream as input, we have an in-built function called getline(). This function is under the <string> header file.
It accepts all the strings until a newline character is encountered.
Inline function
It concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. ... The compiler can ignore the inline qualifier in case defined function is more than a line.