【发布时间】:2016-08-31 19:50:15
【问题描述】:
我已经看到如何从字符串中删除特定字符,但我不确定如何在打开文件的情况下执行此操作,或者您是否可以这样做。基本上一个文件会打开,里面有任何东西,我的目标是删除所有可能出现的字母 a-z、特殊字符和空格,这样剩下的就是我的数字。当文件打开时,您能否轻松删除所有字符而不是指定 a、b、c 等,或者我是否必须将其转换为字符串?在内存中这样做会更好吗?
我的代码如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filename;
cout << "Enter the name of the data file to open" << endl;
cin >> filename >> endl;
ofstream myfile;
myfile.open(filename);
if (myfile.is_open()) { //if file is open then
while(!myfile.eof()){ //while not end of file
//remove all chars, special and whitespace
}
}
else{
cout << "Error in opening file" << endl;
}
return 0;
}
【问题讨论】:
-
为什么不只提取使用isdigit() 的数字而忽略其他所有内容呢?
-
然后,一旦你读入一个字符串,只需获取所有数字字符并将它们写回一个单独的文件。
-
@FirstStep 我只提取数字会弄乱格式吗?这就是为什么我决定不这样做。因为一行可能是 272 而下一行是 345 我不希望它变成 272345
-
@user5468794 但是你说你想删除所有的空格???