使用while(cin>>)计算空格,制表符和换行符

时间:2017-06-03 14:43:56

标签: c++ tabs lines spaces

我的程序有问题,应该计算用户发送到流的字符串中的每个符号。它计算辅音,元音,'ff','fl','fi'和'\ t','\ n'和''。问题是程序工作得很好,但仍然不计算空格,制表符和新行。我试过使用noskipws操纵器,但它不读取任何东西直到第一个单词。

这是:

Component emptySpace = Box.createRigidArea( ... );
panel.add( emptySpace );

2 个答案:

答案 0 :(得分:1)

int tabCount = 0, spaceCount = 0, newlineCount = -1;
while(std::getline(std::cin, line)){ //getline reads in a line to a string tokenized by \d by default
    newlineCount++; //every time there's a new loop, theres a new newline.
    for(auto c : line) {
        if(c == '\t')
            tabCount++;
        else if(c == ' ')
            spaceCount++;
    }
}

您可以使用此基本格式从std :: cin或任何其他输入流逐行读取字符串。 std :: getline会自动通过' \ n'进行标记。所以你可以从-1开始你的换行计数(假设你得到至少一行)并循环你的字符串并计算你想要的任何字符。

答案 1 :(得分:-2)

使用gets()或在现代c ++编译器中使用gets_s()

#include "iostream"
using namespace std;
int main() {
    char x[20];
    gets_s(x);
    for (int i = 0; i < 20; i++) {
        if (x[i] == ' ') {
            cout << i;
        }
    }
    system("pause");
    return 0;
}
相关问题