检查字符中的空白和字符串中的数字
Check white-space in Char and Check Digits in Strings
所以我面临这个问题:
编写一个程序,读取文本文件并检查单词。如果单词仅以字符开头,并且其中不包含任何数字。输入以分号结束;
我试着用两种方式做到这一点:
#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
时,如果可用,>>
将读取下一个字符,否则将失败。
当text
是char
数组时,>>
将读取字符,直到遇到空白、达到最大宽度或失败。
无论哪种方式,>>
都不会返回它跳过的空白。所以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);
相关文章:
- 如何检查一个c++字符串中有多少相同的字符/数字
- 在 c++ 中查找字符串中没有循环的数字总和
- 将数字转换为填充字符串
- 递归形成字符串中所有数字字符的中间和?
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- C++ python 中的函数返回数字而不是字符串
- C++:从文件中读取字符串和整数,并获得最大数字
- 以C++格式将字符串转换为数字
- C++关于数字的字符串数组
- 使用非托管导出将字符串从 C# 返回到C++将返回数字
- 我想使用 std::stoi 函数在 cpp 中将字符串转换为整数,因为我想在字符串中找到不同数字的总和(在下级酶中)
- 将大数字(10-12 位数字)存储在无序映射中<字符串,整数>
- 用C++将浮点数字转换为本地化字符串
- 如何在c++中将字符串中的所有数字保存到多维数组中
- 列出所有 N 位数字,并带有 [字符串] 数字
- 如何将字符串数字转换为各个数字的整数数组
- 如何将字符串/数字排序添加到 QSortFilterProxyModel 派生类
- 将std::字符串数字转换为十六进制数字
- 在c++ /Qt中拆分Lua函数调用的混合字符串/数字参数列表
- 获取字符串数字的精度