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.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I made a code but it doesn't work.Can you help? In code, I wanted to take a line and if code see //n, end line.
Here is my example.
File:
I love C++! //n
My Code:
ifstream file("file.txt");
char text[250];
while(file >> text){
cout << text << " ";
if(text == "//n"){
cout << endl;
}
}
Thanks for your help.
I am unsure as to what you are trying to do, however it seems that you want to get a line worth of text. If so, you would want to change
char text[255];
....
if(text == "//n")
to
std::string text;
...
if(text == "\n")
The array comparison will not compare strings. So use the std::string to allow you to use == operator.
As C++ special character codes use a backslash rather than two forward slashes.
However, I'd also suggest using a single char rather than an array (as indexing doesn't seem to be a concern since you only access the first character in it).
If you want to read a file a word at a time:
ifstream file("file.txt");
std::string line;
while(std::getline(file, line)) {
std::stringstream linestream(line);
std::string word;
while(linestream >> word) {
std::cout << "Word: " << word << " ";
}
std::cout << "EOL\n";
}
Basically your code has a couple of issues.
'//n' is not a special character we all assume you meant '\n'.
Most operators that read text from a file will disgard the '\n' character.
operator>> will disguard white space (including \n).
getline() reads the line but drops the \n.
Thus '\n' is never in text to be compared too.
Arrays char text[255] will convert themselves into pointers easily.
Thus the comparison you are doing compares two pointers. This will never be equal.
You need a type that does something smart with == so that you compare the text.
For this you should use std::string.
As a good style guide.
Never put using namespace std; in your code. It causes more trouble when you have anything but a simple bit of throwaway code. And using it in simple throwaway code is a bad habit that will catch up to you someday.
The reason std (as well as others) is short and not standard is so that prefixing it items from the standard library is not burdensome.
std::cout << text << " "; // not hard.
std::cout << std::endl;
There is no real reason to use std::endl (debugging being an exception I suppose). In normal situations the extra flush it adds will generally cause the output to slow down perceptibly. So prefer to use '\n' unless you specifically want to force a flush.
The problem here is, your code compares pointers, instead of comparing strings (as noted also in the other answer):
if(text == "//n")
{
...
}
Here text is a pointer (actually, an array of char, but in this context it's equivalent to a pointer), and "//n" also is a pointer (also an array). Comparing two pointers is not what you want.
To fix your code so it compares strings, one of the things your code compares should be a string instead of a pointer. To mark "//n" as a string, append s to it:
if(text == "//n"s)
{
...
}
This is a bit obscure; another solution is to make text a string (as described in the other answer):
std::string text;
This question already has an answer here:
Read data from fstream
(1 answer)
Closed 3 years ago.
How can I check if there is more content in a text file in c++ and if there is continue to read it?
I am trying to read a some words from a text file but the number of words is not specified.
Check out this link here.
Also, std:: is a reference to the namespace of code you are calling. When you include a file that is in the standard libraries, such as string, vector, fstream, iostream, you need to either declare that your file will use the namespace std with using namespace std; OR you append std:: to the method or variable.
Use std::vector and std::string. Use a correct form of reading a file:
std::string word;
std::vector<std::string> word_database;
while (text_file >> word)
{
word_database.push_back(word);
}
std::cout << "Words read: " << word_database.size() << "\n";
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
This question already has answers here:
Read a file backwards?
(7 answers)
Closed 8 years ago.
How can I read a text file in reverse order (i.e. from eof) using C++?
Yes, but you basically have to do it manually.
The basic algorithm is as follows:
Seek to the end of the file with is.seekg(0, is.end)
Determine the file size with is.tellg()
Repeatedly seek backwards and read chunks of the file until you reach the front
If the file is small enough so the entire contents easily fit within memory, it will be both far faster and far easier to code to read the file forward into a string and then reversing that string after the fact.
If the contents won't fit in memory, you'll have to use nneonneo's solution. It would probably be best to turn off buffering.
Just use the seekg and related functions in istream class. Here is a working example. Tested.
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream in("file.txt");
// Get the length of the file
in.seekg(0, in.end);
int len = in.tellg();
// Start reading the file in reverse
char c;
while (len--)
{
in.seekg(len, in.beg);
in >> c;
cout << c;
}
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to use istream with strings
std::ifstream ifile(absolute_file_path.c_str(),std::ios::binary | std::ios::in | std::ios::ate);
if (ifile.is_open()==false)
{
throw std::runtime_error("Unable open the file.");
}
std::stirng file_content;
//here I need good way to read full file to file_content
//note: the file is binary
ifile.close();
This are ways I know:
1.Maybe not safe
file_content.resize(ifile.tellg());
ifile.seekg(0,std::ios::beg);
if(!ifile.read(const_cast<char *>(file_content.data()), file_content.size()));
{
throw std::runtime_errro("failed to read file:");
}
ifile.close();
2.Slow
file_content.reserve(ifile.tellg());
ifile.seekg(0,std::ios::beg);
while(ifile)
{
file_content += (char)(ifile.get());
}
If the file is binary, it might contain '\0' which is a weird character to be contained in an std::string. Although I think you could do that, you will be asking for problems because some operations on a std::string take a const char* which is null-terminated. Instead, go with std::vector<char>, a much safer way.
If you go with strings anyway, just do a loop calling std::string::append(size_t, char).
while(!ifile.eof()) {
contents.append(1, ifile.get());
}
EDIT: I think you can also do something in the lines of:
std::string contents(std::istreambuf_iterator<char>(ifile), std::istreambuf_iterator<char>());
You should be clear with binary file and string. Do you mean to read the content of that file, or you want to read binary representation of the file to string? Normally an unsigned char[] buffer is used to store content of binary files. And string is used to store content of a text file.