C++逐字符读取字符串

C++ reading a String character by character

我有一个逐字符读取输入字符串的限制。所以我在每个字符串之后检查 \n 。但是程序没有终止。

这是我在非常短的代码中遇到的问题:

#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;
}

在上面的代码中,c 将具有字符串的第一个字符,而 x 将一个接一个地具有其余字符。

输入大小写:

banananobano
abcdefhgijk
Radaradarada

cin 是用空格分隔的,因此任何空格(包括 \n)都将被丢弃。因此,x 永远不会是

使用 getline for reading line from the input stream and then use istringstream 从行中获取格式化输入。

std::string line;
std::getline(cin, line);
std::istringstream iss(line);
while ( iss >> c) {    
     print the characters;
  }

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

一种逐字符读取的方法是通过 std::basic_istream::get.

如果你定义

char c;

然后

std::cin.get(c);

会将下一个字符读入c

在循环中,您可以将其用作

while(std::cin.get(c))
    <body>