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.
Related
When I read a string with getline method in C++ it's adding a space in front of my string.
What should I do to eliminate that?
This is my code:
void read_from_file(_Longlong mobile_number) {
string number = to_string(mobile_number);
fstream read(number + "messages_not_seen.txt", ios::in);
_Longlong mobile_numer;
string first_name;
string last_name;
char txt[500];
int Priority;
while (read) {
read >> first_name >> last_name >> mobile_numer;
read.getline(txt, 500);
if (read.eof()) {
break;
}
push(mobile_numer, first_name, last_name, txt);
}
}
The >> operator leaves delimiting whitespace in the stream. Usually, it's not a problem because the >> operator will also ignore leading whitespace, but if you use getline() after the extraction, the space will get included into the string.
You can ignore leading spaces with something like
while (std::isspace(static_cast<unsigned char>(std::cin.peek()))) std::cin.ignore();
Or just call cin.ignore() once if you're sure there is exactly one leading space.
Something you might find helpful is the non-member std::getline() function, which works with std::string instead of character arrays.
If you're using modern C++ (C++-11 and up), you can use lambdas in order to do so.
#include <algorithm>
#include <cctype>
#include <locale>
#include <iostream>
using namespace std; // not recommended, but I assume you're a beginner.
// trim from start (in place)
static inline void ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
}
void read_from_file(_Longlong mobile_number)
{
string number = to_string(mobile_number);
fstream read(number + "messages_not_seen.txt", ios::in);
_Longlong mobile_numer;
string first_name;
string last_name;
// char txt[500]; // why are you using C-style char here?
string txt; // use string instead
int Priority;
while (read)
{
read >> first_name >> last_name >> mobile_number;
ltrim(read.get(cin, txt));
if (read.eof())
{
break;
}
push(mobile_numer, first_name, last_name, txt);
}
}
And don't forget the main function where you invoke all of these.
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; }
}
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;
}
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.)
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
}
}