【问题标题】:Reading from a text file to populate an array从文本文件中读取以填充数组
【发布时间】:2015-03-22 21:24:49
【问题描述】:

我的目标是将值存储到文本文件中,然后通过读取文本文件填充数组。

目前,我将值存储到文本文件中;

Pentagon.CalculateVertices();//caculates the vertices of a pentagon

ofstream myfile;
myfile.open("vertices.txt");
for (int i = 0; i < 5; i++){
    myfile << IntToString(Pentagon.v[i].x) + IntToString(Pentagon.v[i].y) + "\n";
}
myfile.close();

我已将值存储到此文本文件中,现在我想从创建的文本文件中填充一个数组;

for (int i = 0; i < 5; i++){
    Pentagon.v[i].x = //read from text file
    Pentagon.v[i].y = //read from text file
}

这就是我现在所拥有的一切;谁能告诉我如何实现代码所说的。

【问题讨论】:

    标签: c++ arrays filestream


    【解决方案1】:

    您无需将int 转换为std::stringchar*

    myfile << Pentagon.v[i].x << Pentagon.v[i].y << "\n";
    // this will add a space between x and y coordinates
    

    这样读:

    myfile >> Pentagon.v[i].x >> Pentagon.v[i].y;
    

    &lt;&lt;&gt;&gt; 运算符是流的基础,你怎么没遇到过?

    您也可以使用自定义格式,例如[x ; y](空格可以省略)。

    写作:

    myfile << "[" << Pentagon.v[i].x << ";" << Pentagon.v[i].y << "]\n";
    

    阅读:

    char left_bracket, separator, right_bracket;
    myfile >> left_bracket >> Pentagon.v[i].x >> separator << Pentagon.v[i].y >> right_bracket;
    
    // you can check whether the input has the required formatting
    // (simpler for single-character separators)
    if(left_bracket != '[' || separator != ';' || right_bracket != ']')
        // error
    

    【讨论】:

    • 所以为了让我将值存储在文本文件中,它们可以是任何“类型”吗?他们不需要是字符串吗?我来自一个背景,基础知识被跳过了。
    • 如果您重载运算符,它们甚至可以接受自定义类。
    • 这是有道理的,否则我们将无法拥有复杂的程序。一个问题,“>>”给了我错误。,我需要
    • @Moynul 你用过std命名空间等吗?
    • @TalhaIrfan 在顶部我有'using namespace std'让编译器提前知道。
    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    相关资源
    最近更新 更多