Using getline to divide input, using commas as delim - c++

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; }
}

Related

C++ Reading Text File and Storing Data

data.txt contains the following information: firstName, lastName, salary, increment.
James Chong 5000 3
Peter Sun 1000 5
Leon Tan 9500 2
I want to read data.txt, make the necessary calculations, and store the output of 3 variables in anewData.txt:
firstName, lastName, updatedSalary(salary*percentageIncrement)
I only managed to proceed to reading and display information in data.
Below is my code:
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
string filename = "data.txt";
ifstream infile;
infile.open(filename);
//if file cannot open, exit program
if (!infile.is_open()){
exit(EXIT_FAILURE);
}
string word;
infile >> word;
while(infile.good()){
cout << word << " ";
infile >> word;
}
system("pause");
return 0;
}
May I know are there any references that I can make use of? Thank you
I am not entirely sure about the question , but you might find substr function useful (if you need to process the data),about writing to a file, you can just create an ofstream output("newData.txt") and simply write the result there. (output << result). Also there is a tokenizer library in BOOST if you don't want to solve it with substr.
You're expecting each line to have 4 words separated by whitespace, so it's as easy as extracting them from infile at each iteration:
while(infile.good()) {
string first_name, last_name;
infile >> first_name;
infile >> last_name;
unsigned int salary, increment;
infile >> salary;
infile >> increment;
}
of course you should check that infile is good after attempting to extract the various pieces, should the lines be malformed.
You can get fancier here, but this covers your basic needs.

No matching function for call to 'get line' while exploding

No matching function for call to 'getline' when using this code:
ifstream myfile;
string line;
string line2;
myfile.open("example.txt");
while (! myfile.eof() )
{
getline (myfile, line);
getline (line, line2, '|');
cout<<line2;
}
In the example.txt i have info like this:
1|Name1|21|170
2|Name2|34|168
etc...
I really want to get the line till the | char...
I try few explode functions but they are only in string type but i need:
1st to be int
2nd to be char
3rd and 4th to be float.
It's really complicated that i want to do, and i can't explain it well. I hope someone will understand me.
getline receives as first argument an instance of the template basic_istream. string doesn't meet that requirement.
You could use stringstream:
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string line;
string line2;
ifstream myfile("test/test.txt");
while (getline(myfile, line))
{
stringstream sline(line);
while (getline(sline, line2, '|'))
cout << line2 << endl;
}
return 0;
}

c++ found an example on splitting strings trying to figure out why change to it changes result

I'm learning about splitting strings for a program in class, and i came across this example.
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string str = "23454323 ABCD EFGH";
std::istringstream iss(str);
std::string word;
while(iss >> word)
{
std::cout << word << '\n';
}
}
I modified so that the user instead inputs the string,but if I input the string stored in str i get 23454323 and not the other material in the string.
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
string str;
cout<<"Enter a postfix with a space between each object:";
cin>>str;
istringstream iss(str);
string word;
while(iss >> word)
{
cout << word << '\n';
}
}
Ok, thanks for the help everyone got it!
You need to modify your input code a little for this to work. Use:
getline(cin, str);
instead of:
cin >> str;
The latter will stop reading a string on whitespace characters.
Because you use the same input operator as for istringstream when you input from cin and it always breaks on whitespace.
That means you only read a single word from the user. You want to use std::getline.
Just as iss >> word reads a single space-separated word from iss, so cin >> str just reads the first word from cin.
To read a whole line, use getline(cin, str).
(Also, get out of the habit of dumping namespace std into the global namespace. It will cause problems as your programs grow.)

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.

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
}
}