RAHUL RAHUL - 2 months ago 17
C++ Question

C++ reading a String character by character

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. I'm just putting 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

Answer

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>