C++;程序未通过字符串输入的cin步骤 显然,我不太明白C++的“文件结尾”概念,因为下面的程序只是不经过“TIME(CIN)X”步骤。每当我从命令行运行它时,它都会坐在那里嘲笑我
在某处和其他地方搜索时,经常提到在windows上按ctrl-z然后按enter键输入文件结尾字符,但这似乎对我不起作用。这让我认为我的问题在别处。也许将x定义为字符串是我的错误?任何关于我在这里哪里出错的建议都会很好 注意:很抱歉代码中没有注释-程序本身应该包含一系列注释 然后吐出每个单词的计数C++;程序未通过字符串输入的cin步骤 显然,我不太明白C++的“文件结尾”概念,因为下面的程序只是不经过“TIME(CIN)X”步骤。每当我从命令行运行它时,它都会坐在那里嘲笑我,c++,input,C++,Input,在某处和其他地方搜索时,经常提到在windows上按ctrl-z然后按enter键输入文件结尾字符,但这似乎对我不起作用。这让我认为我的问题在别处。也许将x定义为字符串是我的错误?任何关于我在这里哪里出错的建议都会很好 注意:很抱歉代码中没有注释-程序本身应该包含一系列注释 然后吐出每个单词的计数 #include <iostream> #include <string> #include <vector> #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
using std::cin;
using std::cout; using std::endl;
using std::sort;
using std::string; using std::vector;
int main()
{
cout << "Enter a series of words separated by spaces, "
"followed by end-of-file: ";
vector<string> wordList;
string x;
while (cin >> x)
wordList.push_back(x);
typedef vector<string>::size_type vec_sz;
vec_sz size = wordList.size();
if (size == 0) {
cout << endl << "This list appears empty. "
"Please try again." << endl;
return 1;
}
sort(wordList.begin(), wordList.end());
cout << "Your word count is as follows:" << endl;
int wordCount = 1;
for (int i = 0; i != size; i++) {
if (wordList[i] == wordList[i+1]) {
wordCount++;
}
else {
cout << wordList[i] << " " << wordCount << endl;
wordCount = 1;
}
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
使用std::cin;
使用std::cout;使用std::endl;
使用std::sort;
使用std::string;使用std::vector;
int main()
{
cout>x)
单词列表。推回(x);
typedef vector::size_type vec_sz;
vec_sz size=wordList.size();
如果(大小==0){
cout如果您在windows上,则^Z必须作为换行符后的第一个字符,如果您在unixy shell上,则需要键入^D。在使用cin时,我几乎总是使用getline(特别是当我需要的是字符串时):
因此,您可以调用getline(cin,x)
,它将获取到新行的所有内容。您必须等待新行,以便cin为您提供任何内容。因此,在这种情况下,您的循环将变成:
while(getline(cin, x))
wordList.push_back(x);
cin
不接受空格或换行符,因此除非您输入一些内容,否则无法完成执行cin
,下面是一个测试程序,它提供您想要的内容
#include "stdafx.h"
#include<iostream>
#include <string>
#include <sstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string str = "";
while(std::getline(cin, str) && str!="")
{
cout<<"got "<<str<<endl;
}
cout<<"out"<<endl;
cin>>str;
return 0;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
int _tmain(int argc,_TCHAR*argv[]
{
字符串str=“”;
while(std::getline(cin,str)&&str!=“”)
{
cout代码的输入部分工作正常。我看到的唯一真正的问题是循环试图计算字数:
for (int i = 0; i != size; i++) {
if (wordList[i] == wordList[i+1]) {
wordList的有效下标从0到大小-1。在循环的上一次迭代中,i=size-1,但随后您尝试使用wordList[i+1]
,索引超出向量末尾,并获得未定义的结果。如果使用wordList.at(i+1)
相反,它会抛出一个异常,快速告诉您有关问题的更多信息
我的猜测是,现在发生的情况是,你正在点击Control-Z,它正在退出输入循环,但当它试图计数单词时崩溃了,所以当你修复时,总体上情况会更好。如果你在修复其他问题后真的无法通过输入循环,并且您在Windows下运行,您可以尝试使用F6而不是进入control-Z,这似乎更可靠。肯定会发布一个新问题,对一个已经有了公认答案的问题的后续评论不会获得很多视图。
for (int i = 0; i != size; i++) {
if (wordList[i] == wordList[i+1]) {