【问题标题】:cutting words in a file and writing while preserving line number in c++ [closed]在c ++中保留行号的同时在文件中剪切单词并写入[关闭]
【发布时间】:2012-05-13 20:14:07
【问题描述】:
 #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]='\0';
    nstr=str.substr(0,str.find_first_of(charr));

    outfile<<nstr<<' ';
 }
}

这个程序使用 substr(0, string.find_first-of(charcter array which is starting point to be substring))每个单词的不必要的子字符串,但在写入另一个文件时它不保留行号。你能修好它吗 。它按顺序逐字写入文件。代码没有逐行保留,

【问题讨论】:

    标签: c++ file inputstream


    【解决方案1】:

    字符串输入不关心行边界,它把 \n,\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';
        }
    }
    

    【讨论】:

    • 谢谢,它对我有用。
    【解决方案2】:

    改变

     outfile<<nstr<<' ';
    

     outfile<<nstr<<endl;
    

    这将逐行写入,而不是与单个空白字符分开。

    【讨论】:

    • 我看到了问题。文件立即读入字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多