Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reading a String character by character

Tags:

c++

iostream

I have a constraint to read the input strings character by character. So I'm checking for \n after each string. But the program is not terminating.

Here's the problem I'm facing in a very short code:

#include <iostream>
using namespace std;

int main()
{
    char c;
    while(cin >> c)
    {                
        char x;
        cin >> x;
        while(x != '\n')
        {       
            // print the characters
            cin >> x;  
        } 
    }
    return 0;
}

In the above code, c will have the first character of the string while x will have the rest of characters one by one.

Input Case:

banananobano
abcdefhgijk
Radaradarada
like image 622
Shashank Avatar asked Dec 31 '25 21:12

Shashank


1 Answers

I have a constraint to read the input strings character by character

One way of reading character by character, is via std::basic_istream::get.

If you define

char c;

then

std::cin.get(c);

will read the next character into c.

In a loop, you could use it as

while(std::cin.get(c))
    <body>
like image 178
Ami Tavory Avatar answered Jan 02 '26 10:01

Ami Tavory