I have a problem. I load the whole file and then getline through it to get some info. However in the map format there may be 0 or 20 "lines" with the info. I need to know how to getline through std::string. There is a function (source stream, destination string, decimal) but I need (source string, destination string, decimal). Searching in streams isn't possible in C++ (only using many temp string and extracting and inserting many times, it's unclear and I don't want to do it that messy way). So I want to know how to getline from a std::string.
Thans
You seem to want std::istringstream, which is in the header <sstream>:
std::string some_string = "...";
std::istringstream iss(some_string);
std::string line;
while (std::getline(iss, line))
{
// Do something with `line`
}
Related
I want to read integers in a line from a file.
For example the line is : 3/2+5-5
I think I need to use >>, but it stopped because of the characters;
I also try to use other functions, but they are all for characters.
As the #Fang already pointed out, there's no easy way to do it. You can read the whole line and tokenize it via the following code:
std::ifstream f("file.txt");
std::string line;
std::getline(f, line);
std::vector<std::string> integers;
boost::split(integers, line, boost::algorithm::is_any_of("+-*/"), boost::token_compress_on);
// Then convert strings from the integers container to ints
I am trying to read text from a file into an array and then output the contents of each array index to the output file. I need the data to be read/stored until it reaches the end of line, at which point it should re-start reading/storing and re-using the array for temporary storage only to be output to the output file.
I cannot use the getline function because the idea is that later I will incorporate the use of some model classes to store the individual words as member variables of the classes. I will need to have the words separated to know which words get saved as which variables. For this reason I need to be able to just identify the corresponding index position and get it's contents.
I know my syntax is incorrect so I was hoping someone knew a correct syntax for recognizing the end of line.
this is what I've tried so far:
ifstream fin;
//open file...
char next[20]; //creating an word array to hold the characters of a word.
fin >> next;
while (!fin == '\n') //<------ THIS IS WHAT I THINK THE PROBLEM IS.
//I KNOW ITS INCORRECT BUT DO NOT KNOW THE CORRECT WAY.
{
//input words, store to array, and output to file
fin >> next;
}
You should use a std::string instead of a char array to handle words of any size. Streams also have an implicit conversion to void* (bool in C++11 or later) to test if the stream is still valid.
std::ifstream fin(filename);
std::string word;
while(fin >> word) {
//do something with word
}
So I've been doing algorithms in C++ for about 3 months now as a hobby. I've never had a problem I couldn't solve by googleing up until now. I'm trying to read from a text file that will be converted into a hash table, but when i try and capture the data from a file it ends at a space. here's the code
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
ifstream file("this.hash");
file >> noskipws;
string thing;
file >> thing;
cout << thing << endl;
return 0;
}
I'm aware of the noskipws flag i just don't know how to properly implement it
When using the formatted input operator for std::string it always stops at what the stream considers to be whitespace. Using the std::locale's character classification facet std::ctype<char> you can redefine what space means. It's a bit involved, though.
If you want to read up to a specific separator, you can use std::getline(), possibly specifying the separator you are interested in, e.g.:
std::string value;
if (std::getline(in, value, ',')) { ... }
reads character until it finds a comma or the end of the file is reached and stores the characters up to the separator in value.
If you just want to read the entire file, one way to do is to use
std::ifstream in(file.c_str());
std::string all((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
I think the best tool for what you're trying to do is get, getline or read. Now those all use char buffers rather than std::strings, so need a bit more thought, but they're quite straightforward really. (edit: std::getline( file, string ), as pointed out by Dietmar Kühl, uses c++ strings rather than character buffers, so I would actually recommend that. Then you won't need to worry about maximum line lengths)
Here's an example which will loop through the entire file:
#include <iostream>
int main () {
char buffer[1024]; // line length is limited to 1023 bytes
std::ifstream file( "this.hash" );
while( file.good( ) ) {
file.getline( buffer, sizeof( buffer ) );
std::string line( buffer ); // convert to c++ string for convenience
// do something with the line
}
return 0;
}
(note that line length is limited to 1023 bytes, and if a line is longer it will be broken into 2 reads. When it's a true newline, you'll see a \n character at the end of the string)
Of course, if you a maximum length for your file in advance, you can just set the buffer accordingly and do away with the loop. If the buffer needs to be very big (more than a couple of kilobytes), you should probably use new char[size] and delete[] instead of the static array, to avoid stack overflows.
and here's a reference page: http://www.cplusplus.com/reference/fstream/ifstream/
This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 8 years ago.
In c++, how can I iterate through each line in a string? There have been plenty of questions regarding reading a file line by line, but how can I do this with a std::string?
For example, if I have the following string:
1051
2232
5152
3821
0021
3258
How would I iterate through each number?
In c++, you can use string exactly as files, using the classes defined in the sstream header:
#include <sstream>
//...
std::string str=...; // your string
std::istrstream in(str); // an istream, just like ifstream and cin
std::string line;
while(std::getline(in,line)){
//do stuff with line
}
This is a bit simplistic, but you get the idea.
You can use in just as you would use cin, e.g. in>>x etc. Hence the solutions from How do I iterate over cin line by line in C++? are relevant here too - you might want to look at them for the "real" answer (just replace cin with your own istream
Edit:
As a side note, you can create strings in the same way you print to the screen, using the ostream mechanism (like cout):
std::ostringstream out;
out << header << "_" << 3.5<<".txt";
std::string filename=out.str();
Use a tokenizer and let '\n' or '\r\n' or the appropriate newline for your OS be the token splitter..
Or if you were using a buffered file stream reader, just create a stringstream from this new string and read from the string stream instead of the file stream.
In short nothing changes except that you aren't reading from a file.
A horribly naive solution would be to make a string stream from this and assign ints or strings in a while loop from it.
I have a space delimited text file, from which I need to extract individual words to populate a vector<string>.
I've tried playing around with strtok, but I understand this is not working because strtok returns a char pointer. Any way to extract the words from the file, and fill the string vector with them? Thanks!
There are "fancier" ways, but in my opinion the following's most understandable (and useful as a basis for variations) for beginners:
if (std::ifstream input(filename))
{
std::vector<std::string> words;
std::string word;
while (input >> word)
words.push_back(word);
}
Consider using an ifstream to read the file.
Then you can use the >> operator to move the next word into the string.