Suppose we have a string line:
14.6527 39.5652 -344.226 -3.34672
Let's call this string, str_line.
My question is, how can we parse this into a float array, float data[4].
I tried using getline from stringstream but to no avail (see below for representation of my code). Any help would be appreciated :)
for(int i=0;i<4;i++){
stringstream ss(str_line);
ss.getline( str_line, 8, ' ' );
data[i]=atof(ss);
}
You should declare stringstream object ss once, don't do it in a loop.
Then you have to only use the operator >> to extract floats from the stream.
stringstream ss(str_line);
for(int i=0;i<4;i++){
ss >> data[i];
}
If you're reading from a file, you can use a file stream like ifstream and read floats directly from it. The stream will ignore any whitespaces including newlines.
Use the >> operator on stringstream:
ss >> data[i];
Related
I've attempted to use atof() (which I think is way off) and stringstream. I feel like stringstream is the answer, but I'm so unfamiliar with it. Based on some Google searches, YouTube videos, and some time at cplusplus.com, my syntax looks like below. I'm pulling data from a .csv file and attempting to put it into a std::vector<double>:
while (file.good() )
{
getline(file,line,',');
stringstream convert (line);
convert = myvector[i];
i++;
}
If you are reading doubles from a stream (file) we can simplify this:
double value;
while(file >> value) {
myvector.push_back(value);
}
The operator>> will read from a stream into the type you want and do the conversion automatically (if the conversions exists).
You could use a stringstream as an intermediate if each line had more information on it. Like a word an integer and a double.
std::string line;
while(std::getline(file, line)) {
std::stringstream lineStream(line);
std::string word;
int integer;
double real;
lineStream >> word >> integer >> real;
}
But this is overkill if you just have a single number on each line.
Now lets look at a csv file.
This is a line based file but each value is seporated by ,. So here you would read a line then loop over that line and read the value followed by the comma.
std::string line;
while(std::getline(file, line)) {
std::stringstream lineStream(line);
double value;
char comma;
while(lineStream >> value) {
// You successfully read a value
if (!(lineStream >> comma && comma == ',')) {
break; // No comma so this line is finished break out of the loop.
}
}
}
Don't put a test for good() in the while condition.
Why is iostream::eof inside a loop condition considered wrong?
Also worth a read:
How can I read and parse CSV files in C++?
I have read a CSV file that has line ending character as '\r', the reading operation done successfully, but the problem started when i pass the read line in to the while(getline(ss,arr2,',')) for separating comma..it does work properly for the first line but all the next iterations are empty(i.e)it has been failing to separate the comma in the string.
int main()
{
cout<<"Enter the file path :";
string filename;
cin>>filename;
ifstream file;
vector<string>arr;
string line,var;
stringstream content;
file.open(filename.c_str(),ios::in );
line.assign((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
file.close();
string arr2;
stringstream ss;
content<<line;
//sqlite3 *db;int rc;sqlite3_stmt * stmt;
int i=0;
while (getline(content,var,'\r'))
{
ss.str(var);//for each read the ss contains single line which i could print it out.
cout<<ss.str()<<endl;
while(getline(ss,arr2,','))//here the first line is neatly separated and pushed into vector but it fail to separate second and further lines i was really puzzled about this behaviour.
{
arr.push_back(arr2);
}
ss.str("");
var="";
arr2="";
for(int i=0;i<arr.size();i++)
{
cout<<arr[i]<<endl;
}
arr.clear();
}
getch();
}
what went wrong in the above...I see nothing right now:(
The stringstream::str method does not reset / clear the internal state of the stream. After the first line, the internal state of ss is EOF (ss.eof() returns true).
Either use a local variable inside the while loop:
while (getline(content,var,'\r'))
{
stringstream ss(var);
Or clear the stream before ss.str:
ss.clear();
ss.str(var);
I want to parse a file which describes a set of data line by line. Each datum consists of 3 or four parameters: int int float (optional) string.
I opened file as ifstream inFile and used it in a while loop
while (inFile) {
string line;
getline(inFile,line);
istringstream iss(line);
char strInput[256];
iss >> strInput;
int i = atoi(strInput);
iss >> strInput;
int j = atoi(strInput);
iss >> strInput;
float k = atoi(strInput);
iss >> strInput;
cout << i << j << k << strInput << endl;*/
}
The problem is that the last parameter is optional, so I'll probably run into errors when it is not present. How can i check in advance how many parameters are given for each datum?
Furthermore,
string line;
getline(inFile,line);
istringstream iss(line);
seems a bit reduldant, how could I simplyfiy it?
Use the idiomatic approach in this situation, and it becomes much simpler:
for (std::string line; getline(inFile, line); ) {
std::istringstream iss(line);
int i;
int j;
float k;
if (!(iss >> i >> j)) {
//Failed to extract the required elements
//This is an error
}
if (!(iss >> k)) {
//Failed to extract the optional element
//This is not an error -- you just don't have a third parameter
}
}
By the way, atoi has some highly undesired ambiguity unless 0 is not a possible value for the string you're parsing. Since atoi returns 0 when it errors, you cannot know if a return value of 0 is a successful parsing of a string with a value of 0, or if it's an error unless you do some rather laborious checking on the original string you had it parse.
Try to stick with streams, but in situations where you do need to fall back to atoi type functionality, go with the strtoX family of functions (strtoi, strtol, strtof, etc). Or, better yet, if you're using C++11, use the stoX family of functions.
You could use a string tokenizer How do I tokenize a string in C++?
In particular: https://stackoverflow.com/a/55680/2436175
Side note: you do not need to use atoi, you could simply do:
int i,j;
iss >> i >> j;
(but this wouldn't handle alone the problem of optional elements)
How do you read in a double from a file in C++?
For ints I know you can use the getline() and then atoi, but I am not finding an array to double function. What is available for reading in doubles, or converting a char array to a double?
You can use stream extraction:
std::ifstream ifs(...);
double d;
ifs >> d;
This work provided that other then whitespace, the next data in the stream should be a double in textual representation.
After the extraction, you can check the state of the stream to see if there were errors:
ifs >> d;
if (!ifs)
{
// the double extraction failed
}
Do not consider using atof(), or any of the ato.. functions, as they do not allow you to diagnose errors. Take a look at strtod and strtol. Or use the stream extraction operators.
I'm wondering, does one need to be careful about locale settings (e.g. a locale could use comma instead of dot to separate the decimal part) or do stringstreams always default to some standard "C locale" notation?
You can leverage istringstream For example, here are toDouble and toInt:
double toDouble(string s) {
double r = 0;
istringstream ss(s);
ss >> r;
return r;
}
int toInt(string s) {
int r=0;
istringstream ss(s);
ss >> r;
return r;
}
While reading a file (ifstream), is there any way to direct it to make a new line?
For instance, I would like for THIS to happen:
myfile>>array[1]>>array[2]>>endl;
Obviously, the "endl" just isn't allowed. Is there another way to do this?
Edit---thanks for the quick responses guys!
From a text file, I'm trying to store two strings from that file into arrays and then do the same with the next line (or until I desire, using a for loop)
Using strings is important to me as it will make my future program a lot more flexible.
Several options:
You can use ignore.
myfile >> array[1] >> array[2];
myfile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Or you can read each line into as string stream
std::string line;
std::getline(myfile,line);
std::stringstream stream(line);
stream >> array[1] >> array[2];
Please note: Array indexing starts at 0.
Use std::getline to read a line into a memory stream, then get the two strings from that.
while (cin)
{
string line;
getline(cin, line);
stringstream stream;
stream << line;
stream >> array[1]>>array[2];
}
Read your two items, then call myfile.ignore(8192, '\n')
I have no idea what this question means. Here's a simple way to read all the lines of a file into a vector of strings. It might be easier to do what you want to do if you do this first.
std::vector<std::string> lines;
std::string line;
while (std::getline(myFile, line))
lines.push_back(line);
Now you can say lines[4] to get the fifth line, or lines.size() to find out how many lines there were.
This should work:
stringstream stream;
string sLine;
int iLine;
while (cin)
{
getline(cin, sLine);
stream << sLine;
stream >> data[iLine][0] >> data[iLine][1];
}
Customized version of an earlier answer.