iterate through lines in a string c++
Here's a straight-forward solution. Maybe not the most efficient, but unless this is hot code or the string is huge, it should do fine. We suppose that your input string is called input
:
#include <string>
#include <sstream>
std::string result;
std::istringstream iss(input);
for (std::string line; std::getline(iss, line); )
{
result += ">> " + line + "\n";
}
// now use "result"
Is there a C++ iterator that can iterate over a file line by line?
EDIT: This same trick was already posted by someone else in a previous thread.
It is easy to have std::istream_iterator
do what you want:
namespace detail
{
class Line : std::string
{
friend std::istream & operator>>(std::istream & is, Line & line)
{
return std::getline(is, line);
}
};
}
template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
typedef std::istream_iterator<detail::Line> InIt;
std::copy(InIt(is), InIt(), dest);
}
int main()
{
std::vector<std::string> v;
read_lines(std::cin, std::back_inserter(v));
return 0;
}
C++: How to iterate over a text in a std::string line by line with STL?
Why do you keep the text in your source file? Keep it in a separate text file. Open it with std::ifstream and iterate over it with while(getline(...))
#include <iostream>
#include <fstream>
int main()
{
std::ifstream fin("MyText.txt");
std::string file_line;
while(std::getline(fin, file_line))
{
//current line of text is in file_line, not including the \n
}
}
Alternatively, if the text HAS to be in a std::string
variable read line by line using std::istringstream
in a similar manner
If your question is how to put the text lexially into your code without using +, please note that adjacent string literals are concatenated before compilation, so you could do this:
std::string text =
"Line 1 contents\n"
"Line 2 contents\n"
"Line 3 contents\n";
How to iterate over the words of a sentence in C++?
Before you can iterate over words in a sentence, you need to read a sentence from input. This line
cin >> sentence;
reads the first word of a sentence, not the whole sentence. Use getline
instead:
std::getline(std::cin, sentence);
With sentence
in memory, you can iterate it word-by-word using istream_iterator
as follows:
stringstream ss(sentence);
for (auto w = istream_iterator<string>(ss) ; w != istream_iterator<string>() ; w++) {
string &word = *w;
...
}
Demo.
C++ reading input from cin until the whole line has been read
Now that you clarified your question it's way clearer. And @TeoZec answer should be right. I just wanna note two things that seem buggy in your above code:
else if (c == '-')
{
num.push(a+b);
count--;
}
here you probably wanted a-b
instead.
if (count>1)
{
b = num.top();
a = num.top();
num.pop();
num.pop();
b
and a
will be the same number here, you should call pop()
before getting the second number, like:
if (count>1)
{
b = num.top();
num.pop();
a = num.top();
num.pop();
Iterating over lines in a string?
You can use std::getline.
std::string line;
while(std::getline(file, line)) {
// Ohai!
}
While loop skips cin.getline() for C-string
This happens, because the failbit
is set, see std::basic_istream::getline
Behaves as UnformattedInputFunction. After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):
- end of file condition occurs in the input sequence (in which case setstate(eofbit) is executed)
- the next available character c is the delimiter, as determined by Traits::eq(c, delim). The delimiter is extracted (unlike basic_istream::get()) and counted towards gcount(), but is not stored.
- count-1 characters have been extracted (in which case setstate(failbit) is executed).
This means, when more than N
characters are entered by the user, the delimiter is not found and N+1-1
characters have been extracted.
C++ Loop for String
Your for
loop is missing the declaration and (iteration) expression parts:
for (declaration-or-expression; declaration-or-expression; expression)
so it should have looked like this:
for (;x != '1';) {
which is generally written as
while (x != '1') {
- That would cause problems though since it would not stop directly when the user entered
1
. - You are also comparing an
int
with achar
('1'
), so in order to exit the loop, the user would have had to enter49
(the ASCII value for1
), not1
. - You are also mixing formatted input (
cin >> x
) with unformatted input (getline
). I suggest that you stick to one only.
Example:
while(cout << "Enter 1 to stop\n", getline(cin, input) && input != "1") {
bookQ.push_back(input);
}
Related Topics
How to Pass a Member Function Where a Free Function Is Expected
Finding C++ Static Initialization Order Problems
Is Returning by Rvalue Reference More Efficient
How to Handle Wrong Data Type Input
Getting a File* from a Std::Fstream
Pointer Expressions: *Ptr++, *++Ptr and ++*Ptr
Installing Opencv 2.4.3 in Visual C++ 2010 Express
Difference Between an Int and a Long in C++
How to Use Queryperformancecounter
Difference Between _Tmain() and Main() in C++
C++ Static Initialization Order
Sfinae Working in Return Type But Not as Template Parameter
What Is the Lifetime of the Result of Std::String::C_Str()