C ++在CSV文件中搜索单词

时间:2017-12-05 16:40:24

标签: c++ csv vector

我正在尝试创建一个程序,用于存储CSV文件中的数据,然后在其中搜索关键字。 我有这个代码,并没有显示错误,但它不会运行程序过去要求'输入单词:'

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>

using namespace std;


int main(){

    vector<string> student(860);
    vector<string> question(860);
    vector<string> answer(860);

    int count = 0;
    string word;

    ifstream file("data2.csv");

    if (!file.is_open())
        cerr << "File not found" << endl;

    while (file.good()){

        for (int i = 0; i < 860; i++){

            getline(file, student[i], ',');
            getline(file, question[i], ',');
            getline(file, answer[i], ',');
        }
    }

    cout << "Enter word: ";
    cin >> word;

    for (int j = 0; j < 860; j++){
        if (answer[j].find(word) != std::string::npos){
            cout << student[j] << question[j] << answer[j] << endl;
            count++;
        }
    }

    cout << count;

    return 0;
}

3 个答案:

答案 0 :(得分:0)

为了让std::cin包含用户输入的确切字符串(多个单词?),您可以使用std::getline()来支持用户指定的多个单词。如果这是你想要的,你的问题陈述中不清楚。否则,如果您要查找的只是一个输入词,我就不会发现只使用std::cin的问题。

std::string match;
std::cout << "Enter the exact string to search for: ";
std::getline(std::cin, match);
std::cout << "\nSearching for \"" << match << "\"" << std::endl;

此外,在for循环中搜索答案字符串时,您应该更喜欢使用您循环的矢量的内置大小而不是硬编码值。

for ( size_t j = 0; j < answer.size(); ++j )
{
    std::size_t found = answer[j].find(match);
    if (found != std::string::npos)
    {
        std::cout << "found \"" << match
            << "\" starting at character " << found << std::endl;
        count++;
    }
}
std::cout << "occurrences of match criteria: " << count << std::endl;

答案 1 :(得分:0)

错误在getline,第一次调用它,直到逗号第二次调用直到第二个逗号,3r调用第三个逗号到第二个新行(下一个学生的名称)。

因此getline调用中的下一次迭代会将question作为students名称,然后answer作为question,然后是下一个students {1}} answer的名字,一团糟!!! ;)所以你永远找不到你要找的单词,因此没有结果。得到它?

要解决此问题,请尝试将上一个getline更改为getline(file, answer[i]);

答案 2 :(得分:0)

所以,我知道这不是解决问题的最佳方法。但是,在时间紧迫的时候,我能够修复这些错误并添加一个系统(“暂停”);在我的代码结束时,它会让我看到结果。

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>

using namespace std;


int main(){

    vector<string> student(860);
    vector<string> question(860);
    vector<string> answer(860);

    int count = 0;
    string word;

    ifstream file("data2.csv");

    if (!file.is_open())
        cerr << "File not found" << endl;

    while (file.good()){

        for (int i = 0; i < 860; i++){

            getline(file, student[i], ',');
            getline(file, question[i], ',');
            getline(file, answer[i], '\n');
        }
    }

    cout << "Enter word: ";
    cin >> word;

    for (int j = 0; j < 860; j++){
        if (answer[j].find(word) != std::string::npos){
            cout << student[j] << question[j] << answer[j] << endl;
            count++;
        }
    }

    cout << count << endl;
    system("pause");

    return 0;
}
相关问题