std :: cout在for循环内不起作用 [英] std::cout not working inside a for-loop
问题描述
我是C ++的新手,现在我正在学习《 加速的C ++ 》一书。我完成了第三章(向量),然后开始了本练习:
I'm new to C++, and right now I'm learning from the book called Accelerated C++. I finished the third chapter (vectors), and I came to this exercise:
编写一个程序,计算每个单词在其输入中出现的次数。
"Write a program to count how many times each distinct word appears in its input."
经过一番思考,我开始研究它。我想测试该程序,但std :: cout无法正常工作。我把 cout<< test;
在我的代码中的几个地方查看问题出在哪里,结论是它在第一个for循环内不起作用。不建议我使用地图来解决问题,因为我正在研究矢量。变量不是英语的,所以我将翻译一些变量,让您了解发生了什么事情。
After some thinking, I started working on it. I wanted to test the program, but std::cout wasn't working. I put cout << "test";
on a few places in my code to see where's the problem, and the conclusion is that it doesn't work inside the first for-loop. Don't recommend me to use maps to solve the problem, because I'm working on vectors. The variables aren't in English, so I'll translate some for you to know what's going on:
recenica-句子; rijec-一个字; vel_vektora-向量的大小; duz_recenice-句子的长度; br_ponavljanja-单词在句子中出现的次数;
recenica - the sentence; rijec - a word; vel_vektora - size of the vector; duz_recenice - length of the sentence; br_ponavljanja - number of times a word appears in the sentence;
#include <vector>
#include <iostream>
#include <string>
using std::string; using std::vector;
using std::cin; using std::cout;
using std::endl;
int main()
{
string rijec;
vector<string> recenica;
while (cin >> rijec) recenica.push_back(rijec);
cout << endl;
typedef vector<string>::size_type vel_vektora;
vel_vektora duz_recenice = recenica.size();
cout << "test0, ";
for (int i = 0; i < duz_recenice - 1; ++i)
{
cout << "test, !";
int br_ponavljanja = 1;
for (int j = i + 1; j < duz_recenice; ++j)
{
cout << "test2, ";
if (recenica[i] == recenica[j])
{
cout << "test3, ";
++br_ponavljanja;
recenica.erase(recenica.begin() + j);
}
cout << "test4, ";
}
cout << recenica[i] << ": " << br_ponavljanja << endl;
}
cout << "test5, ";
getchar();
return 0;
}
std :: cout <有什么问题
?
推荐答案
添加<< flush
刷新输出缓冲区(每个位置)。
Add << flush
to flush your output buffer (each place).
或使用<< endl
,都添加换行符和刷新。
Or use << endl
, which both adds newline and flushes.
代码存在问题,特别是对于空输入,但这就是你要解决的问题了解有关信息,所以我会留给您! :-)
There are problems with the code, especially for empty input, but that's what you're out to learn about, so I'll leave you to it! :-)
干杯hth。,
这篇关于std :: cout在for循环内不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!