c++ - 不明白为什么 C++ 程序没有输出

标签 c++

我正在做 Accelerated C++ 练习 3-3,但我终究无法弄清楚为什么我的程序没有输出。我什至尝试一路添加测试 cout,但它没有给我任何东西。为什么即使在主 for 循环之外添加 cout 语句,它也不会产生任何输出?

#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <vector>

using std::cout;        using std::cin;
using std::endl;        using std::vector;
using std::sort;        using std::string;

int main() {
    int count = 0;
    string input;
    vector<string> words;
    typedef vector<string>::size_type vec_sz;
    vec_sz size = words.size();

    cout << "Sentence: ";
    while(cin >> input) {
        words.push_back(input);
    }

    for(int i = 0; i < size - 1; i++) {
        for(int j = 0; j < size - 1; j++) {
            if(words[i] == words[j]) {
                ++count;
            }
        }
        cout << "The word " << words[i] << " appears " << count << " times." << endl;
    }
    return 0;
}

最佳答案

您可以检查 size == 0。因此,for 循环中没有任何迭代。

要修复它,您需要将行 vec_sz size = words.size(); 降低几行。

试试这个顺序:

cout << "Sentence: ";
while(cin >> input) {
    words.push_back(input);
}

vec_sz size = words.size();

您的 for 循环中的逻辑也存在错误。您需要每次重置 count(只需在内部循环之前添加 count = 0; 以获得正确的结果)。

你可以在这里查看它是如何工作的:http://ideone.com/T2cPcH (count初始化错误)

关于c++ - 不明白为什么 C++ 程序没有输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42639995/

相关文章:

c++ - C++ 中的超时变量使用什么类型?

c++ - 无法在派生类中定义嵌套类成员函数

c++ - 无法在 vc++ mfc 应用程序中分配 1.5GB 内存

C++将数据从数据文件输入到结构变量中

c++ - 为同一个指针变量重复调用复制构造函数内存泄漏?

c++ - #include 重复查找的任何工具?

C++ 字符减法

c++ - 常规的c++程序头文件结构?

c++ - 复制构造函数未被调用

c++ - 我可以更改 Code::Blocks 自动缩进的行为吗?