C++ 当按下enter键时,如何使数组停止读取字符?
我是编程新手,似乎不知道如何解决这个问题。我的作业很简单,只使用strcmp函数按字母顺序排列两个单词 我的程序可以编译并运行,但直到我用字符完全填充数组,程序才会运行,但我们应该能够使用不同长度的单词 以下是我写的:C++ 当按下enter键时,如何使数组停止读取字符?,c++,strcmp,C++,Strcmp,我是编程新手,似乎不知道如何解决这个问题。我的作业很简单,只使用strcmp函数按字母顺序排列两个单词 我的程序可以编译并运行,但直到我用字符完全填充数组,程序才会运行,但我们应该能够使用不同长度的单词 以下是我写的: #include <iostream> #include <string.h> using namespace std; int main() { int x; char wordone[10] , wordt
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int x;
char wordone[10] , wordtwo[10];
cout << "Please enter your first word: \n";
for(x=0; x<10; x++) cin >> wordone[10];
cout << "Please enter the second word: \n";
for(x=0; x<10; x++) cin >> wordtwo[10];
if(strcmp(wordone, wordtwo)<0)
{
cout << wordone << endl << wordtwo;
}
if ( strcmp( wordone,wordtwo)>0)
{
cout << wordtwo << endl << wordone;
}
else
{
cout << wordone << endl << wordtwo;
}
return 0;
}
And the output looks like this:
Please enter your first word:
help
me
please
Please enter the second word:
hello
how
`
@
àu0þ
#包括
#包括
使用名称空间std;
int main()
{
int x;
char-wordone[10],wordtwo[10];
cout-wordone[10];
coutwordtwo[10];
if(strcmp(wordone,wordtwo)用于输入。使用getline或直接获取输入。
而不是这个-
cout << "Please enter your first word: \n";
for(x=0; x<10; x++) cin >> wordone[10];
还是这样做
string s;
cin>>s; // simply take input like ordinary variable. Rember to #include<string>
使用std::getline
而不是>
流式传输到一个没有被检查是否失败的变量。将cin>>wordone[10]
更改为cin>>wordone[x]
作为第二个输入。感谢您的回复,我正在尝试此操作,但它给出了一个错误:调用–getline没有匹配的函数(std::istream&,char&)for(x=0;xIf我使用wordone和wordtwo[x]程序运行了,但我仍然有相同的问题,如下所示:请输入第一个单词:hello hello请输入第二个单词:help hello s hellohello hello hello hellohelphellos@hellohello你好@[谢谢!我尝试了第一种解决方案,它的效果与我所寻找的完全一样。很好,但也要记住这些。有时你会遇到一些有用的情况。
string s;
cin>>s; // simply take input like ordinary variable. Rember to #include<string>
string s; // for getline this is must. Use string
getline(cin,s);