C++ while, for and array

C++ while, for and array

本文关键字:and array for while C++      更新时间:2023-10-16

嘿,伙计们,我一直在做一项作业,要求写一个列出文件内容的程序。

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

您不需要两个循环。

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

您的任务是

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

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

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

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

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

但关键是要使用while循环,因为

可能多于或少于3个项目