【发布时间】:2017-01-10 20:05:20
【问题描述】:
我的项目需要一个文件名并打开它。我需要读取 .txt 文件的每一行,直到出现第一个数字,跳过空格、字符、零或特殊字符。我的文本文件可能如下所示:
1435 //1, nextline
0 //skip, next line
//skip, nextline
(*Hi 245*) 2 //skip until second 2 after comment and count, next line
345 556 //3 and count, next line
4 //4, nextline
我想要的输出一直是 9,但我把它浓缩了:
Digit Count Frequency
1: 1 .25
2: 1 .25
3: 1 .25
4: 1 .25
我的代码如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
int digit = 1;
int array[8];
string filename;
//cout for getting user path
//the compiler parses string literals differently so use a double backslash or a forward slash
cout << "Enter the path of the data file, be sure to include extension." << endl;
cout << "You can use either of the following:" << endl;
cout << "A forwardslash or double backslash to separate each directory." << endl;
getline(cin,filename);
ifstream input_file(filename.c_str());
if (input_file.is_open()) { //if file is open
cout << "open" << endl; //just a coding check to make sure it works ignore
string fileContents; //string to store contents
string temp;
while (!input_file.eof()) { //not end of file I know not best practice
getline(input_file, temp);
fileContents.append(temp); //appends file to string
}
cout << fileContents << endl; //prints string for test
}
else {
cout << "Error opening file check path or file extension" << endl;
}
在这种文件格式中,(* 表示注释的开始,因此从那里到匹配的*) 的所有内容都应该被忽略(即使它包含一个数字)。例如,给定输入(*Hi 245*) 6,应计算6,而不是2。
如何遍历文件只找到第一个整数并计算它,而忽略 cmets?
【问题讨论】:
-
为什么输出中没有
0?你的意思是第一个数字,还是第一个整数的所有数字?此外,您需要两个单独的循环(输入和输出)。至少打印你应该已经想到了。 -
例子看不懂,文中出现了不止一次
-
使用
std::getline创建一个使用std::isdigit的手写循环。vector<int> file_nums {infile_begin, eof};没有意义。eof是一种完全不同类型的迭代器,即使是std::istreambuf_iterator<char>,你也不会解析任何东西。 -
好的,我想我明白你想做什么了。问题是什么?
-
您现在真的应该忘记该行的来源(文件,键盘,无关紧要),并编写一个给定字符串的函数,返回您的数字寻找。然后您测试该功能以查看是否确实完成了这项工作。一旦您对该功能进行了全面测试,然后您就可以在更大的程序中使用它。尝试一次性完成 3 或 4 个不同的任务并不是渐进式开发程序的方法。