Basically I have a thread reading from c++ std::istream using
istream& getline ( istream& is, string& str );
And when I bind the istream with cin, then it works fine when I type the input from standard command line as the input.
But I am wondering is there a way that I can make the read thread getline get the string without
using the actual command line ?
Basically I want to achieve this:
By just calling a function WriteToIStream with parameter str (instead of type str in command line) and the read thread getilne() can get the str.
void WriteToIStream(string& str)
{
//...
}
Many Thanks
cin is only one instance of an input stream, bound to the standard input. For your case, you can use an istringstream (or more generally a stringstream) which is an input stream to read from a string:
std::istringstream istr("foobar");
getline(istr, some_string_variable);
This requires the standard header <sstream>.
Related
I don't understand the design decisions behind the C++ getline function.
Why does it take a stream and a string by reference as arguments, only to return the same stream that was passed in? It seems more intuitive to only take the stream as an argument, then return the string that was read. Returning the same stream lets you chain the call, but would anyone really want to use getline(getline(stream, x), y)?
Additionally, why is the function not in the std namespace like the rest of the standard library?
If the function returned a string, there would be no way of indicating that the read failed, as all string values are valid values that could be returned by this (or any other) function. On the other hand, a stream has lots of error indicator flags that can be tested by the code that calls getline. So people can write code like:
while( std::getline( std::cin, somestring )) {
// do stuff with somestring
}
and it is hard to see how you could write similar code if getline returned a string.
why is the function not in the std namespace like the rest of the standard library?
It is in the std namespace - what makes you think otherwise?
Why does it take a stream and a string by reference as arguments, only to return the same stream that was passed in?
It is a common pattern in the stream library to do that. It means you can test the operation being performed as you perform it. For example:
std::string line;
while(std::getline(std::cin, line))
{
// use line here because we know the read succeeded
}
You can also make succinct parsers by "chaining" stream functions:
std::string key, value;
if(std::getline(std::getline(in, key, '='), value))
my_map[key] = value;
It seems more intuitive to only take the stream as an argument, then return the string that was read.
The problem with returning a new string every call is that you are constantly allocating new memory for them instead of reusing the memory already allocated to the string you passed in or that it gained while iterating through a loop.
// Here line will not need to allocate memory every time
// through the loop. Only when it finds a longer line than
// it has capacity for:
std::string line;
while(std::getline(std::cin, line))
{
// use line here because we know the read succeeded
}
I know I know.
This question has been asked before, but I've looked at all the answers and none seem to solve my problem. When I use the getline function to get the contents of a line in the file, it doesn't work.
getline(file, line);
'File' is declared here:
ifstream File;
File.open("fruit.txt");
and 'line' is declared here:
int line = 0;
Getline is underlined in red with this message:
getline
no instance of overloaded function "getline" matches the argument list
argument types are :(std::ifstream, int)
What this means is no instance of getline has the argument list of the file stream and an integer.
This makes no sense as all the other questions on this matter state exactly that, that the arguments are the file stream and an integer.
What am I doing wrong?
EDIT:
Here is the full code:
ifstream fruitFile;
fruitFile.open("fruit.txt");
int line = 0;
int C_FRUIT = getline(fruitFile, line);
fruitFile.close();
The first line should be a number, and I need it.
getline() will read one line of text. It can't read directly an int. This is why you get your error message.
You have to be aware that there are two getline(). There is one which is istream::getline() and std::getline(). Both have different signatures. The first is a member function of a stream and is defined in the stream header; the latter is defined in the <string> header.
But pay attention: the return value of std::getline() is not an int ! It's a stream reference. This is why you get a second compiler error.
Finally if you want to read an integer x, it's easier to use extractors:
int value;
fruitFile >> value;
fruitFile.ignore(SIZE_MAX, '\n'); // in case you'd need to go to next line
Or if you really want to read an int in a full line:
string line;
getline(fruitFile, line);
stringstream sst(line); // creates a string stream: a stream that takes line as input
sst >> value;
The second argument of getline needs to be a string: http://www.cplusplus.com/reference/string/string/getline/
I think what you try to achieve is:
ifstream fruitFile;
fruitFile.open("fruit.txt");
int line = 0;
fruitFile >> line
fruitFile.close();
I faced the same error. add this to your code to solve the problem
Add the string library
include <string>
Add the below function call, where string_variable should be of type string.
std::getline(cin, sting_variable)
I'm a beginner making a program in Eclipse IDE (C++) and I've got a problem with a small piece of my code. The problem is shown below:
char dataArray[100];
cout<<"Please enter a data set string: ";
cin.getline(dataArray,100,'\n');
cout<<dataArray;
When I run it the program gets stuck at the getline command, whatever the input, it just lets me input characters indefinitely without continuing.
You are reading data from input stream or from dataArray ? Standard format of getline is
istream& getline (istream& is, string& str, char delim);
Where is is istream object from which characters are extracted
std::string data;
std::getline (std::cin,data);
try this.
I am new to programming and I have this question. I have this file that I am opening
ifstream fin;
FILE * pFile;
pFile = fopen (fname,"r");
The file has 3 data each line. The first is an integer, the second is an alphabet and the third is an address(like computer memory address). How do I extract these line by line into 3 variables that I can process, and then repeat it with next line and so.
You should know that there are preferred C++ methods for manipulation of files over C stdio methods:
Using standard predefined streams: std::ofstream for output and std::ifstream for input.
Formatted/Unformatted I/O such as operator<<(), operator>>(), read() and write().
In-memory I/O for manipulation of extracted data.
What you need for this particular case is input stream functionality along with formatted input. The formatted input will be done through operator>>().
But before you get to that, you have to instantiate a file stream. Since you're using input, std::ifstream will be used:
std::ifstream in("your/path.txt");
The next thing to do is to create the three variables whose values you will extract into the stream. Since you know the types beforehand, the types you will need is an integer, character, and string respectively:
int num;
char letter;
std::string address;
The next thing to do is to use operator>>() to obtain the first valid value from the stream. The way it works is that the function analyses the type of the righthand operand and determines if the characters extracted from the file stream will create a valid value after parsing. When the stream hits whitespace, the new line character or the EOF (end-of-file) character (or a character that doesn't match that of the operand's type), extraction will stop.
What makes IOStreams powerful is that it allows chaining of expressions. So you are able to do this:
in >> num >> letter >> address;
which is equivalent to:
in >> num;
in >> letter;
in >> address;
This is all that is needed for this simple case. In more complex situations, loops and in-memory I/O might be needed for successful extractions.
I am trying to understand what exactly the following function is doing. It is used to read a text file into a struct, called AEntry, which only contains four ints.
The file contains a list of lines. Each line holds four ints delimited with spaces (or tab).
when this function is called, a line of istream and a AEntry struct are passed in.
My question is how the delimitors, spacess or tabs, are filtered out? or my understanding is wrong.
istream& operator>>( istream &stream, AEntry& val )
{
stream >> val.kv;
stream >> val.col;
stream >> val.bo;
stream >> val.Offset;
return stream;
}
They're filtered out because that's the behavior of the default overloads of istream::operator>>. They stop at whitespace and discard it instead of incorporating it into the extracted output.