【问题标题】:C++ while, for and arrayC++ while、for 和数组
【发布时间】:2015-03-26 23:00:47
【问题描述】:

大家好,我一直在做一个任务,我要求编写一个列出文件内容的程序。

#include<iostream>
#include<fstream>
using namespace std;
int main() {

string array[5];

ifstream infile("file_names.txt");

int x=0;
while(infile>>array[x++]){

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

    infile >> array[i];

    cout << array[i] << endl;}}

    }

基本上我有一个名为“file_names.txt”的文件,其中包含三个字符串,我希望我的程序列出它们。

【问题讨论】:

  • 您尝试了 A,预期 B,并观察了 C。描述 A、B 和 C
  • “我卡住了”具体在哪一点?
  • 如果你只想列出一些字符串,你不需要嵌套循环,也不需要数组。

标签: c++ arrays loops for-loop while-loop


【解决方案1】:

你不需要两个循环。

int main() {
int array_size=5;
string array[array_size];

ifstream infile("file_names.txt");

int x=0;int i=0;
while(i<array_size && infile>>array[i]){ //order is important here
    cout << array[i] << endl;
    i++;
    }

}

【讨论】:

  • infile &gt;&gt; array[i] 应该是循环条件,否则这几乎和checking eof 一样糟糕
  • @MattMcNabb 感谢专业提示。
  • @JackArcher 行动胜于雄辩。标记答案。
【解决方案2】:

你的任务是

我要求编写一个列出文件内容的程序的作业。

打印文件内容的一种方法是

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

using namespace std;

int main()
{
    ifstream fin("my_file.txt", ios::in); // open input stream

    if(!fin){ // check state, that file could be successfully opened
        printf("Error opening file.");
        return 1;
    }

    while(fin.peek() != EOF){
        cout << (char)fin.get();
    }

    fin.close(); // close input stream

    return 0;
}

这段代码演示了一些基本的 C++ 功能,例如 打开输入流,检查输入流的状态并逐字符读取内容。试着理解每一步。

【讨论】:

    【解决方案3】:

    我知道我可以得到同样的结果

    string array[50];
    
    ifstream infile("file_names.txt");
    
    for(int i=0; **i<3**; i++){
    
        infile >> array[i];
    
        cout << array[i] <<endl;}
    

    但重点是使用 while 循环,因为可能多于或少于 3 个项目

    【讨论】:

      猜你喜欢
      • 2020-09-18
      • 2011-07-19
      • 1970-01-01
      • 2010-10-07
      • 2017-05-15
      • 2011-03-21
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      相关资源
      最近更新 更多