由于某些原因,此代码在获取多个输入后将输出int的大小。我是c++的初学者,如果有人可以帮助我并帮助我了解为什么会发生,我将非常感激。谢谢。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int calculateVowelIndex(std::string input)
{
float numVowel = 0, numCon = 0;
int vowelIndex;
std::vector<char> vowels{ 'a', 'e', 'i', 'o', 'u', 'y' };
std::transform(input.begin(), input.end(), input.begin(), ::tolower);
for (int x = 0; x < input.length(); ++x)
{
if (std::find(vowels.begin(), vowels.end(), input[x]) != vowels.end())
++numVowel;
else
++numCon;
}
vowelIndex = numVowel / (numVowel + numCon) * 100;
return vowelIndex;
}
int main()
{
int n;
std::string input;
std::vector<std::string> words;
std::vector <unsigned int> vowelIndexes;
std::cin >> n;
for (int x = 0; x < n; ++x)
{
std::getline(std::cin, input);
words.push_back(input);
vowelIndexes.push_back(calculateVowelIndex(input));
}
for (int x = 0; x < words.size(); ++x)
{
std::cout << vowelIndexes.at(x) << " " << words.at(x) << std::endl;
}
std::cin.get();
}
最佳答案
我的最佳猜测是,发生这种情况的原因是,当您输入输入内容时,最终会有一条多余的换行符,然后被std::getline
的第一次迭代所吞噬。输入输入的单词数后,std::cin
的缓冲区如下所示:
"3\n"
std::cin >> n;
解析整数并在到达换行符时停止,将其保留在std::cin
中:"\n"
然后,对
std::getline
的第一次调用将读取所有字符(此处没有字符),直到到达换行符('\n'
),然后读取并丢弃,在std::cin
中不保留任何字符。因此,在第一个迭代中将读入空白行并将其传递给函数。剩下两个循环的迭代。接下来的两次
std::getline
调用没有要从std::cin
读取的输入,因此它会提示您更多信息,并且循环将相应地对其进行处理。这就是发生这种情况的原因:读取了一个被遗忘的换行符,并将其作为空行的结尾。
为了解决这个问题,我们必须读取该行中所有剩余的字符,并在读取更多行之前将其丢弃。这可以通过
ignore
上的 std::cin
方法完成,如下所示:// ...
std::cin >> n;
// skip the rest of the line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (int x = 0; x < n; ++x)
// ...
std::numeric_limits
在<limits>
中。这将读取并丢弃每个字符,直到遇到换行符,然后再读取并丢弃。或者,因为看起来您只想要一个单词,为什么不只使用读取一个单词的方法呢?
std::cin >> input;
关于c++ - 随机打印出int的大小,不知道为什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43913767/