请各位大侠帮忙解决下面的问题
已经在文本中写入了一些内容,请问怎么样把其中的年龄项增加1
C++
学号 姓名 性别 年龄 所在系
95001 李勇 男 20 CS
95003 刘晨 女 19 IS
95003 王敏 女 18 MA
95004 张立 男 19 IS
[解决办法]
从文件中读取,修改后,然后重新写入···
[解决办法]
一行一行的读取,修改后再写回文件中,代码如下:
#include <stdexcept>#include <fstream>#include <string>#include <vector>using std::cout;using std::ifstream;using std::string;using std::ofstream;using std::vector;using std::runtime_error;using std::endl;int main(){string s;vector<string> vec;ifstream in;in.open("abc.txt",ifstream::in);//abc.txt是文件名try{if(!in){throw runtime_error("unable to open the file:abc.txt");}}catch(runtime_error &e){cout <<e.what()<< endl;}int i,j,temp = 0;while(!in.eof()){getline(in,s);i = s.size()-1;while((s[i] < '0' || s[i] >'9')&& i>=0)--i;j = i;while(s[j] >='0' &&s[j]<='9' && j>=0)--j;++j;while(j<=i){temp = temp *10 +(s[j] - '0'); ++j;}while(temp && !s.empty()){s[i]=temp%10; temp /=10;--i;} vec.push_back(s);}in.close();in.clear();ofstream out;out.open("abc.txt",ofstream::out);try{if(!out)throw runtime_error("unable to open the file:abx.txt");}catch(runtime_error &e){cout << e.what() << endl;}vector<string>::iterator ite = vec.begin();for(;ite != vec.end();++ite)out << *ite << endl;out.close();return 0;}
[解决办法]
while(temp && !s.empty())
将这一句中的 !s.empty()改成 while(temp && i>=0)就完善了
[解决办法]
上面的代码可以直接运行的
[解决办法]
while(temp && !s.empty())
将上面这一句改成while(temp && i>=0)就完善了
[解决办法]