输出一个语句中的第一个字母
问题描述:
我试图在C++中打印每个单词的第一个字母。我的想法是,首先打印字符串的第一个字母,然后打印每一个字母后有一个空格:输出一个语句中的第一个字母
#include <string.h>
#include <stdio.h>
#include <iostream>
using namespace std;
string sentence;
int main(int argc, char const *argv[])
{
cout << "Input your name!" << endl;
cin >> sentence;
//output first character
cout << sentence[0] << endl;
//output the rest of first characters in words
for(int i = 0; i < sentence.length(); i++){
if (sentence[i] == ' ' && sentence[i+1]!= '\0'){
cout << sentence[i+1]<< endl;
}
}
return 0;
}
此解决方案仅打印字符串的第一个字母,我遇到了麻烦,确定出了什么错我的代码。
答
std::cin
将在第一个空格后停止读入字符串。所以,如果您输入hello world
,它只会将"hello"
读入您的字符串。相反,你可以使用std::getline
阅读整条生产线到您的字符串:
cout << "Input your name!" << endl;
getline(cin, sentence);
...
此外,std::string
的内容将不会有一个空字符('\0'
)在它无论使用哪种方法,让你的sentence[i+1] != '\0'
检查韩元永远不会阻止你印刷一些东西。
+0
谢谢Xymostech!它现在变得更有意义:) –
std :: string中没有'\ 0'。 – Tempux
尝试访问'i + 1'元素将导致出现'出界'错误,如果您使用'.at()' – Tempux
谢谢sudomakeinstall2您的评论!我会记住这一点 –