【问题标题】:read the some data in txt file and pass it to string array读取txt文件中的一些数据并将其传递给字符串数组
【发布时间】:2019-02-18 05:13:52
【问题描述】:

我在windows 7中使用VS2010编写C++ mfc程序。我想逐行读取一个txt文件并将其传递给字符串数组。

我尝试了 testByLine 函数,但它显示名称“fstream”未识别。此外,“ios::in”在我的 Windows 7 中似乎不正确,但我不知道如何更正。

#include "stdafx.h"
#include <fstream>

std::string Value_2[5];

void testByLine()
{
    char buffer[256];
    fstream outFile;
    outFile.open("result.txt", ios::in);
    int i = 0;
    while (!outFile.eof()) {

        outFile.getline(buffer, 128, '\n');
        Value_2[i] = buffer;
        i += 1;
    }
    outFile.close();
}

我希望 txt 中的每一行都被传递给字符串数组 Value_2 的每个元素。

【问题讨论】:

标签: c++


【解决方案1】:

你可以做这样的事情。

#include <fstream> 
#include <iostream>
#include <string>

int main(){

    std::string read;
    std::string arr[5];
    std::ifstream outFile;
    outFile.open("test.txt");

    int count = 0;

    //reading line by line 
    while(getline(outFile, read)){

        //add to arr
        arr[count] = read;
        count++;
    }

    outFile.close();

    //c++ 11
    // for(std::string str : arr) std::cout << str << "\n";
    for(int i = 0; i < 5; i++){
        std::cout << arr[i] << "\n";
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-12
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    相关资源
    最近更新 更多