[英]How to open any input file whether it contains words or numbers and prints it out. C++
所以說這就是輸入文件包含的內容
12
你好
45
54
100
起司
23
我將如何按順序在屏幕上打印出來。 這就是我所擁有的,但是跳過了一些行。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int number;
string word;
int loop = 0;
ifstream infile;
infile.open("arraynumbers.txt");
while(infile >> number >> word)
{
if( infile >> number)
{
cout << number << endl;
}
if(infile >> word)
{
cout << word << endl;
}
}
return 0;
}
我建議使用www.cplusplus.com回答這些問題。
但是,您的方向正確。 由於您只是將文件內容輸出到stdout,因此建議使用readline()和字符串。 如果您需要以整數形式訪問數字字符串,請使用atoi()函數。
例:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream file("arraynumber.txt");
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else cout << "Error opening arraynumber.txt: File not found in current directory\n";
return 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.