How can I std::getline() a string? - c++

Let say I have this string
string myString = "This is a test string:value1/value2/value3/"
How can I do something like this:
getline (myString, temp, '/');
I was thinking about output << myString to a file, and then using
getline (output, temp, '/') as usual, but I think there should be other ways.
Thanks, please help me.

getline extracts from a stream; so you want to put your string into a string-stream:
#include <sstream>
std::stringstream ss(myString);
getline(ss, temp, '/');

Related

Using getline to divide input, using commas as delim

I have a text file with movie info, separated by commas. I will provide a line for insight:
8,The Good the Bad and the Ugly,1966,2
I need to take this line, and divide the different pieces by their comma to fit the format of this function:
void addMovieNode(int ranking, std::string title, int releaseYear, int quantity);
The text file's information is in order with the function but I am unclear on how the getline operation operates.
I know I can pass in the text file like
getline("moveInfo.txt", string, ",");
but how will that translate in terms of what is actually going on with the output?
I read the manual on the cplusplus website but that did not help to clarify very much.
You can use a string and stringstream:
#include <sstream>
#include <string>
#include <fstream>
ifstream infile( "moveInfo.txt" );
while (infile)
{
std::string line;
if (!std::getline( infile, line,',' )) break;
std::istringstream iss(line);
int ranking, releaseYear, quantity;
std::string title;
if (!(iss >> ranking >> title >> releaseYear >> quantity)) { break; }
}

Won´t read whitespace with ifstream

I am relatively new to C++, so be gentle.
I have a text-file I want to read, but when i read the file it skips the whitespace (space) between separated words.
I tried to take away as much junk-code as possible so it would be easier to read.
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
int main(.....)
{
ifstream in_file;
string filename;
string status;
readStringToMem(in_file, status);
cout << "Type in the filename : ";
getline(cin, filename);
in_file.open(filename);
readStringToMem(in_file, status);
}
void readStringToMem(ifstream& in_file, string& string_value)
{
string input_string;
getline(in_file, input_string, '|');
stringstream myInputStream(input_string);
myInputStream >> string_value;
}
My file may look like this:
Status is ok | 100
But when I read it, it comes out like this:
Status 100
Thanks in advance! Any help will be great!
You are trying too hard, this
void readStringToMem(ifstream& in_file, string& string_value)
{
string input_string;
getline(in_file, input_string, '|');
stringstream myInputStream(input_string);
myInputStream >> string_value;
}
should be this
void readStringToMem(ifstream& in_file, string& string_value)
{
getline(in_file, string_value, '|');
}
Much simpler, in fact readStringToMem is so simple I wonder if it's worth putting into a separate function.
I think you were probably confused by the integer case. In that case you have to convert the string you have read with getline to an integer. And you would do that using stringstream. But in the string case you already have a string so there is no conversion to do and no need for stringstream.

C++ getline() jumped over empty strings

I'm reading with my c++ program csv file:
abc;def;ghi
10;;10
by this code:
while(getline(in, str, '\n')){
stringstream ss;
while(getline(ss, str, ';')){
line.add(str);
}
}
Where in is input file, str is string variable and line is my collection (like vector). But getline jumped over the empty string in csv file.
Can anyone help me to reading empty string, too?
Thanks :)
You've never initialized your stream!
Try this:
#include <string> // for std::string and std::getline
#include <sstream> // for std::istringstream
for (std::string jimbob; std::getline(in, jimbob); )
{
std::istringstream marysue(jimbob); // !
for (std::string charlie; std::getline(marysue, charlie, ';'); )
{
line.add(charlie);
}
}

is it possible to read from a specific character in a line from a file in c++?

Hey all so I have to get values from a text file, but the values don't stand alone they are all written as this:
Population size: 30
Is there any way in c++ that I can read from after the ':'?
I've tried using the >> operator like:
string pop;
inFile >> pop;
but off course the whitespace terminates the statement before it gets to the number and for some reason using
inFile.getline(pop, 20);
gives me loads of errors because it does not want to write directly to string for some reason..
I don't really want to use a char array because then it won't be as easy to test for the number and extract that alone from the string.
So is there anyway I can use the getline function with a string?
And is it possible to read from after the ':' character?
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
string fname;
cin >> fname;
ifstream inFile;
inFile.open(fname.c_str());
string pop1;
getline(inFile,pop1);
cout << pop1;
return 0;
}
ok so here is my code with the new getline, but it still outputs nothing. it does correctly open the text file and it works with a char array
You are probably best to read the whole line then manipulate the string :-
std::string line;
std::getline(inFile, line);
line = line.substr(19); // Get character 20 onwards...
You are probably better too looking for the colon :-
size_t pos = line.find(":");
if (pos != string::npos)
{
line = line.substr(pos + 1);
}
Or something similar
Once you've done that you might want to feed it back into a stringstream so you can read ints and stuff?
int population;
std::istringstream ss(line);
ss >> population;
Obviously this all depends on what you want to do with the data
Assuming your data is in the form
<Key>:<Value>
One per line. Then I would do this:
std::string line;
while(std::getline(inFile, line))
{
std::stringstream linestream(line);
std::string key;
int value;
if (std::getline(linestream, key, ':') >> value)
{
// Got a key/value pair
}
}

What am I missing? GetLine function (C++)

string GetLine()
{
char parameter[26] = {NULL};
inFile.getline (parameter,26,' ');
return parameter;
}
Now an example of my input file looks like this:
~in.txt~
BAC BCA(space after the last A)
~End File~
I have to have that space after the A or else my function to get line won't work. Is there a way to not have a space after the A and still get it to work?
I have 26, because the input line will only have up to 26 letters in it.
I need to have them separated like I have it because this is how I use it:
string in, post;
in = GetLine();
post = GetLine();
Thanks for any suggestions on this, this is very small chunk of code for the program i'm still working on. I just wanna cover my bases because my Professor is testing this program with his own input file and I don't know if his input file will end with a space.
This is kind of a silly redundant function, and I don't know why you would call it "GetLine", but here ya go:
string GetLine()
{
string s;
infile >> s;
return s;
}
Perhaps you should just get the line allowing \n to be the delimiter and then just iterate through and tokenize the input by spaces.
Something like this is a much smarter way to do this:
ifstream file(filename);
string line;
if (file)
{
string token;
stringstream iss;
while ( getline(file, line) )
{
iss << line;
while ( getline(iss, token, ' ') )
{
cout << token << endl;
}
iss.clear();
}
}
The EOF and getline don't get along terribly well, so I found this online a few semesters ago when working on a simple parsing problem.
If you know that in and post will have the same length, then here is a solution:
Give GetLine() a char parameter, say delim, that determines the delimiter character.
string GetLine(char delim=' ')
And have it used in the getline call:
inFile.getline (parameter,26,delim);
Then read the lines like this:
string in, post;
in = GetLine(' ');
post = GetLine('\n');
EDIT:
If you don't know whether their will be a space at the end or not, use this:
string GetLine()
{
char parameter[26] = {NULL};
inFile.getline (parameter,26,' ');
string str = parameter;
if (str[str.length()-1]==' ') str.resize(str.length()-1);
return str;
}