写一个程序,它可以读入不超过100个字符的句子,并输出句子,其中的空格已更正,字母的大小写也已更正。换句话说,在输出句子中,包含两个或多个空格的所有字符串都应该压缩为一个空格。句子应以大写字母开头,但不应包含其他大写字母。不要担心正确的名字;如果他们的第一个字母改为小写,那是可以接受的。将换行符视为空白,即将换行符和任意数量的空格压缩为一个空格。假设句子以句点结尾,并且不包含其他句点。例如,输入
生命、宇宙和万物的答案是42。
应产生以下输出:
生命、宇宙和万物的答案是42。
#include<iostream>
#include<string>
using namespace std;
int main()
{
const int MAX = 100;
char sentence[MAX+1];
string replace = "";
int space = 0;
cout<<"Enter a sentence";
cin.getline(sentence,MAX+1);
int i =0;
while(i<MAX && sentence[i] != '\0' && sentence[i] != '.')
{
if(isspace(sentence[i]) || sentence[i] == '.')
{
space++;
}
else{
space = 0;
}
if(space < 2)
{
replace += tolower(sentence[i]);
}
}
if(replace.length()>0)
{
replace.at(0) = toupper(replace.at(0));
if(replace[replace.length()-1]=='' && replace.length()==1){
replace=replace;
}
else if(replace[replace.length()-1]=='')
{
replace[replace.length()-1]='.';
}
else if(replace.length()==MAX)
{
replace[MAX-1]='.';
}
else
{
replace+='.';
}
}
cout<<"The sentence to enter: "<<endl << sentence<<endl;
cout<<"How it should be: "<<replace<<endl;
return 0;
}我的错误是:
Errors:
warning: unknown escape sequence '\O'
[-Wunknown-escape-sequence]
while(i<MAX && sentence[i] != '\O' && sentence[i] != '.')
^~
] warning: empty character constant [-Winvalid-pp-token]
if(isspace(sentence[i]) || sentence[i] == '')
^
error: expected expression
warning: empty character constant [-Winvalid-pp-token]
if(replace[replace.length()-1] == '' && replace.length()=='')
^
33:35: error: expected expression
warning: empty character constant [-Winvalid-pp-token]
if(replace[replace.length()-1] == '' && replace.length()=='')我该如何修复这些问题?
发布于 2019-11-10 03:21:18
if(replace[replace.length()-1]=='' && replace.length()==1){
replace=replace;
}我不知道您在这里要做什么,但是''不是一个有效的字符,它是编译器错误的根源。我不知道您是在寻找null char \0还是别的什么,但是由于整个表达式的结果是replace=replace,所以上面的代码基本上是不需要的。
发布于 2019-11-10 03:25:45
Compilation results on GodBolt。
您实际上没有收到关于'\O'的错误-并且您的代码没有'\O'...它有'\0`` (zero instead of big-Oh). '\0 actually has a meaning -C风格字符串的终止字符,它的整数值是0;但没有转义序列'\O'。
而且,没有“空的单个字符”这样的东西,所以''是没有意义的。在编写代码时,尝试更明确地描述您正在检查的是什么。例如,如果我要写:
bool my_string_ends_with_a_period = (not my_string.empty()) and (my_string.back() == '.');我说的是我正在计算的东西。你不必总是这么冗长,但是现在你的代码有点杂乱,所以很难弄清楚你想要做什么。
https://stackoverflow.com/questions/58782566
复制相似问题