C++ while、for 和数组

C++ while, for and array

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

#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" 的文件,其中包含三个字符串,我希望我的程序列出它们。

您的作业是

an assignment in which I asked to write a program that lists the contents of a file.

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

#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++ 功能,例如 打开输入流,检查输入流的状态并逐字符读取内容。尝试理解每一步。

你不需要两个循环。

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++;
    }

}

我知道我可以得到与此相同的结果

string array[50];

ifstream infile("file_names.txt");

for(int i=0; **i<3**; i++){

    infile >> array[i];

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

但关键是要使用 while 循环,因为可能会多于或少于 3 个项目