C++ while, for and array
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"的文件,其中包含三个字符串,我希望我的程序列出它们。
您不需要两个循环。
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循环,因为
相关文章:
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 为什么 Clang 不允许"and"作为函数名称?
- 位阵列上的快速AND运算
- 是否可以在 C++03 中定义'move-and-swap idiom'等效项
- C++11 中不同类型的对象的 std::array 的替代方案
- constexpr begin of a std::array
- C++如果必须在编译时确定大小,std::array 有什么意义?
- BoostPython and CMake
- OpenSSL BIO and SSL_read
- OpenGL VBO Indexing ( How to compute Index Array)
- 标准::unordered_map 中的 std::array 的值初始化
- "Warning: Comma within array index expression"但逗号分隔函数参数
- Arduino array and if statement
- getline() and char array
- C++ while, for and array
- Concatenate boost::array and std::string
- emplace and unordered_map<?, std::array<?, N>>
- std::array and lambda
- std::cout and printf array