检查 Char 中的 white-space 和检查字符串中的数字
Check white-space in Char and Check Digits in Strings
所以我遇到了这个问题:
Write a program that reads a text file and checks for correctness of
the word. A word is correct if it starts with a character only and
does not contain any number in it. The input ends with a semi-colon
;
我尝试通过两种方式做到这一点:
#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;
}
但这在 space 秒时无法递增。
我尝试使用字符串而不是字符进行相同的尝试,单词计数器可以工作,但是 text == "0"
(例如)也不能正常工作..
为什么 Char 不读取白色-space,为什么 String 不读取数字?
cin >> text
忽略前导空格。
当 text
是单个 char
时,>>
将读取下一个可用字符,否则失败。
当 text
是一个 char
数组时,>>
将读取字符,直到遇到空格、达到其最大宽度或失败。
无论如何,>>
不会 return 它跳过的空格。所以 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);
所以我遇到了这个问题:
Write a program that reads a text file and checks for correctness of the word. A word is correct if it starts with a character only and does not contain any number in it. The input ends with a semi-colon ;
我尝试通过两种方式做到这一点:
#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;
}
但这在 space 秒时无法递增。
我尝试使用字符串而不是字符进行相同的尝试,单词计数器可以工作,但是 text == "0"
(例如)也不能正常工作..
为什么 Char 不读取白色-space,为什么 String 不读取数字?
cin >> text
忽略前导空格。
当 text
是单个 char
时,>>
将读取下一个可用字符,否则失败。
当 text
是一个 char
数组时,>>
将读取字符,直到遇到空格、达到其最大宽度或失败。
无论如何,>>
不会 return 它跳过的空格。所以 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);