从某个文本文件中检索所有数字
Retrieving all numbers from a certain text file
我有以下程序:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
void tellen ()
{
ifstream input;
ofstream output;
char kar;
input.open ("test",ios::in);
kar = input.get();
while ( !input.eof() ){
if ( kar >= '0' and kar <= '9'){
cout << kar;
kar = input.get();
}
else
kar = input.get();
}
//cout << "Aantal characters:" << aantalchar << endl;
//cout << "Aantal regels:" << aantalregels << endl;
}
int main()
{
tellen();
return 0;
} //main
我想让这个程序做的是在命令窗口中显示某个文本文件(在本例中为"Test")中的所有数字。我想知道为什么这不起作用?我有一个名为test的文件,但是当我运行这个文件时,命令提示符给了我一个空白。当我将"test"更改为"test.txt"时,问题仍然存在。有人知道是什么问题吗?也许这和文件的位置有关?
下面的代码将给出一个名为test的txt文件的输出。
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
void tellen() {
ifstream input;
ofstream output;
int kar;
char charKar;
input.open("test.txt", ios::in);
// could replace "test.txt" with a variable such as filePath = "/downloads/test.txt"
if (input.is_open()) {
while (!input.eof()) {
kar = input.get(); //kar gets inputed as an ASCII
charKar = static_cast<char>(kar);//charKar converts the ASCII into a char variable
if (charKar >= '0' && charKar <= '9'){ //Evaluate charKar, not kar
cout << charKar << endl;
}
}
input.close();
}
else {
cout << "nFile Did Not Open!";
}
}
int main() {
tellen();
return 0;
} //main
我已经测试了代码,它的工作!抱歉,如果它是混乱的,我正在制作鸡蛋,而编码这个,所以如果你有任何问题,请问!
需要改变的地方:
-
添加检查以确保文件已成功打开
-
使用
istream::get()
而不是char
读取字符时使用int
类型 -
稍微改变一下
while
语句
void tellen (){
ifstream input;
ofstream output;
input.open ("test",ios::in);
if ( !input )
{
std::cerr << "Unable to open file.n";
return;
}
int kar; // Don't use char.
while ( (kar = input.get()) != EOF ){
if ( kar >= '0' and kar <= '9'){
cout.put(kar); // I prefer this.
// cout << (char)kar;
}
}
//cout << "Aantal characters:" << aantalchar << endl;
//cout << "Aantal regels:" << aantalregels << endl;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 使用VerQueryValue检索应用程序的文件描述
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- 检索数字短语
- 在C++中,从只知道起始数字(但需要整行)的文本文件中检索某一行
- 如何通过位掩码存储和检索3位数字
- 从某个文本文件中检索所有数字
- 如何检索文件数字签名信息