c++ - 从文本文件读取到数组

标签 c++ arrays sorting fstream

我只是一个C++初学者

我想将文本文件(最多 1024 个单词)读取到一个数组中,我需要忽略所有单字符单词。你们能帮我丢弃单字符的单词以避免符号、特殊字符吗?

这是我的代码:

#include <fstream>
#include <string>
#include <iostream>
using namespace std;

const int SIZE = 1024;

void showArray(string names[], int SIZE){
    cout << "Unsorted words: " << endl;
    for (int i = 0; i < SIZE; i++){
        cout << names[i] << " ";
        cout << endl;
    }
    cout << endl;
}
int main()
{
    int count = 0;
    string names[SIZE];

    // Ask the user to input the file name
    cout << "Please enter the file name: ";
    string fileName;
    getline(cin, fileName);
    ifstream inputFile;
    inputFile.open(fileName);

    // If the file name cannot open 
    if (!inputFile){
        cout << "ERROR opening file!" << endl;
        exit(1);
    }

    // sort the text file into array
    while (count < SIZE)
    {
        inputFile >> names[count];
        if (names[count].length() == 1);
        else
        {
            count++;
        }
    }
    showArray(names, SIZE); // This function will show the array on screen 
    system("PAUSE");
    return 0;
}

最佳答案

如果将 names 更改为 std::vector,则可以使用 push_back 填充它。您可以像这样填写 names

for (count = 0; count < SIZE; count++)
{
    std::string next;
    inputFile >> next;
    if (next.length() > 1);
    {
        names.push_back(next);
    }
}

或者,您可以将所有单词填入 names,然后使用 Erase–remove idiom .

std::copy(std::istream_iterator<std::string>(inputFile),
          std::istream_iterator<std::string>(),
          std::back_inserter<std::vector<std::string>>(names));

names.erase(std::remove(names.begin(), names.end(), 
                [](const std::string& x){return x.length() == 1;}), names.end());

关于c++ - 从文本文件读取到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46599863/

相关文章:

c++ - 返回文本文件 C++ 上的一行

c++ - Boost:我们如何为 TCP 服务器指定 "any port"?

scala - 将 Java 与 Scala 混合使用可变 TreeMap

c++ - 类型别名中的详细类型说明符

c++ - 为什么 Windows 的 gflags 不会因这段代码而崩溃?

java - Java中逐行写入Json对象数组

c - 程序的 CPU 使用率突然飙升,看起来像是暂停了

ruby - 如何确保一个方法返回一个数组,即使在 Ruby 中只有一个元素

c - 如何按字母顺序对字符串数组(二维数组)进行排序?

linux - 排序选项前面的数字表示法指的是什么?