在 C++ 中剪切文件中的单词和书写,同时保留行号

cutting words in a file and writing while preserving line number in c++

本文关键字:书写 保留 单词 C++ 文件      更新时间:2023-10-16
 #include<fstream>
 #include<iostream>
 #include<string>
 #include<algorithm>
 using namespace std;
 int main(){
 ifstream infile;
 ofstream outfile;
 infile.open("oldfile.txt");
 outfile.open("newfile.txt");
 while(infile){
    string str,nstr;
    infile>>str;
    char charr[10];
    charr[0]='<';charr[1]='';
    nstr=str.substr(0,str.find_first_of(charr));
    outfile<<nstr<<' ';
 }
}

该程序使用 substr(0, string.find_first-of(字符数组,它是子字符串的起点))每个单词不必要的子字符串,但在写入另一个文件时它不会保留行号。 你能解决它吗. 它按顺序逐字写入文件。 代码没有逐行保留,

字符串

输入不关心行边界,它将,\t,\v和其他可能与空格相同。

#include <sstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string line,word;
    char foo[] = "<";
    while ( getline(cin,line) ) {
        string newline;
        for ( istringstream words(line)
            ; words >> word ; ) {
                newline+=word.substr(0,word.find_first_of(foo))+' ';
        }
        cout << newline << 'n';
    }
}

更改

 outfile<<nstr<<' ';

 outfile<<nstr<<endl;

这将逐行写入,而不是使用单个空格字符。