C++ reading a String character by character

18,111

Solution 1

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>

Solution 2

cin is whitespace delimited, so any whitespace (including \n) will be discarded. Thus, x will never be

Use getline for reading line from the input stream and then use istringstream to get formatted input from the line.

std::string line;
std::getline(cin, line);
std::istringstream iss(line);
while ( iss >> c) {    
     print the characters;
  }
Share:
18,111
Shashank
Author by

Shashank

Updated on June 07, 2022

Comments

  • Shashank
    Shashank almost 2 years

    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