代码之家  ›  专栏  ›  技术社区  ›  Mark Lalor

C++附加到字符串并写入文件

  •  3
  • Mark Lalor  · 技术社区  · 14 年前

    为什么下面的代码不起作用

    #include <iostream>
    #include <fstream>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    using namespace std;
    
    int main(){
        string data;
        int i=0;
    
        while(i <= 5){
          i++;
          data += i;
          data += "\n";
        }
    
        ofstream myfile;
        myfile.open ("data.txt");
        myfile << data;
        myfile.close();
    }
    

    应该 然后 (这还不存在)

    文件应该是这样的。。。

    1
    2
    3
    4
    5
    

    5 回复  |  直到 14 年前
        1
  •  11
  •   Kirill V. Lyadvinsky    14 年前

    为什么不使用 operator<<

    ofstream myfile;
    myfile.open ("data.txt");
    for ( int i = 1; i <= 5; ++i )
      myfile << i << "\n";
    myfile.close();
    
        2
  •  2
  •   John Dibling    14 年前

    你的代码有多个问题。首先,你是 #include -正在删除几个不推荐使用的标头,包括 <stdio.h> 哪个应该是 <iostream> , <string.h> 哪个应该是 <string> <stdlib.h> <cstdlib> .

    至于你的具体问题,它正在做你要求它做的事情。问题是,你没有要求它做你想做的事 通缉犯 这是我必须做的。在你的代码里 data += i; 你说的是“附加二进制值 i 为了这个 string

    您要做的是将整数转换为它们的字符串表示形式,并将其附加到文本文件中。一个简单的方法是使用 stringstream ,因此:

    #include <iostream>
    #include <fstream>
    #include <iostream>
    #include <string>
    #include <sstream>
    #include <cstdlib>
    using namespace std;
    
    int main(){
        int i=0;
    
            stringstream ss;
        while(i <= 5){
          i++;
                ss << i << endl;
        }
    
        ofstream myfile;
        myfile.open ("data.txt");
        myfile << ss.str();
        myfile.close();
    }
    
        3
  •  1
  •   James    14 年前


    您实际需要的是整数的字符版本,它需要如下内容:

    while(i <= 5){
      i++;
      data += char(i+48);
      data += "\n";
    }
    

    它的作用是将从十进制表示的偏移量(48)添加到 ASCII 数字的表示。
    编辑: 测试了这个,如果你想打印到6或不你也要更换 while(i <= 5) 用一个 while(i < 5)

        4
  •  1
  •   James Curran    14 年前

    我不相信运算符+=(int)是为std::string定义的,所以 data += i; 如果它编译的话,会被翻译成:

     data += (char) i;
    

    让我们在这里使用实际字符:

    char i='0';   
    
    while(i <= '5'){   
      i++;   
      data += i;   
      data += "\n";   
    } 
    

    此外,你还包括 <string.h> 这是字符串的C运行时库(这里的字符串是小整数数组);实际上需要包括 <string> 它是STD::String的C++库。据我所知,您根本不需要stdio.h、stdlib.h或string.h。

        5
  •  1
  •   codaddict    14 年前

    或者,您也可以将sprintf用作:

        char temp[10]; // assuming your string rep of the number won't take >9 char.
    
        while(i <= MAX){
                i++;
                sprintf(temp,"%d",i);
                data += temp;
                data += "\n";
        }