检查字符中的空白和字符串中的数字

Check white-space in Char and Check Digits in Strings

本文关键字:字符串 数字 空白 检查 字符      更新时间:2023-10-16

所以我面临这个问题:

编写一个程序,读取文本文件并检查单词。如果单词仅以字符开头,并且其中不包含任何数字。输入以分号结束;

我试着用两种方式做到这一点:

#include<iostream>
using namespace std;
int main()
{
    char text;
    cout<<"Enter a group of words ending with a semicolon ; ";
    cin>>text;
    int ctr=0;
    while(text !=';')
    {
     if (text  == ' ')   ctr++;
        cin>>text;
    }
    cout<<ctr;

    return 0;
}

但这并不能在空间上递增。

我使用Strings而不是Chars尝试了同样的方法,单词计数器可以工作,但text == "0"(例如)也不能正常工作。。

为什么Char不读取空白,为什么String不读取数字?

cin >> text忽略前导空格。

text是单个char时,如果可用,>>将读取下一个字符,否则将失败。

textchar数组时,>>将读取字符,直到遇到空白、达到最大宽度或失败。

无论哪种方式,>>都不会返回它跳过的空白。所以text永远不会等于' '。此外,你的计数器应该计算实际阅读的单词,而不是它们之间的空格。

试试类似的东西:

#include <iostream>
#include <iomanip> 
#include <string.h>
using namespace std;
int main()
{
    cout << "Enter a group of words ending with a semicolon ; ";
    char text[512];
    int ctr = 0;
    while (cin >> setw(512) >> text)
    {
        if (strcmp(text, ";") == 0) break;
        ++ctr;
    }
    cout << ctr;
    return 0;
}

也许最简单的方法是将输入读取到std::string中,然后搜索不在一组有效字符中的字符。

例如:

const std::string valid_characters = "abcdefghijklmnopqrstuvwxyz"
                                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string text_from_input;
std::getline(std::cin, text_from_input);
std::string::size_type position_of_invalid_char =
    text_from_input.find_first_not_of(valid_characters);