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
Related
I have a 9x8 textfile with no spaces in between the characters. How can I open this text and read it and put it into a 2d vector with characters? What i have so far is this...
#include <iostream>
#include <fstream>
std::ifstream in_str("inputtxt.txt");
std::string line;
while (std::getline(in_str,line))
{}
std::vector<std::vector<std::string>> replacements;
I'm still trying to figure out how to set it up still and adding the file into the vector
How about something like this:
std::array<std::array<char, 8>, 9> characters;
std::string line;
size_t pos = 0;
while (std::getline(in_str, line))
{
std::copy(std::begin(line), std::end(line),
std::begin(characters[pos++]);
}
This will read lines from the input file, and copy all characters into the array.
Note: The above code have no error handling, no checks for the input actually being valid, and most importantly of all there's no checks for going out of bounds of the arrays. If there are more lines of input than expected, or more characters per line than expected, you will get undefined behavior.
Another possible solution, if you're happy to store strings (which of course can be accessed using array-indexing syntax like arrays/vectors), you could do e.g.
std::array<std::string, 9> characters;
std::copy(std::istream_iterator<std::string>(in_str),
std::istream_iterator<std::string>(),
std::begin(characters));
Same disclaimer as for the first code sample applies here too.
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 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`
}
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.