C++将int转换为字符串?

标签 c++ string compiler-construction int

<分区>

我试图将 int 转换为 string ,但它不起作用我不知道为什么...... 这是我的代码:

#include <stdio.h>
#include <stdlib.h>  
#include <iostream>
#include <array>


using namespace std;


int main()
{
    struct Studentendaten {
        int matrnr;
        string name;
        string vorname;
        string datum;
        float note;
    };
    Studentendaten stud;
    array<Studentendaten,100> studArray ;   

  FILE * pFile;
  int ch; 
  int mnr;
  string sub;
  string sub1;
  string sub2;
  string sub3;
  string sub4;
  string sub5;

  int i = 0;
  int pos ;

  pFile=fopen("studentendaten.txt","r");  
  if (pFile==nullptr) 
  {
      perror ("Fehler beim öffnen der Datei");
  }
  else
  {       
    while (ch != EOF) 
    {
      ch = fgetc(pFile);
      sub += (char)(ch);
      pos = sub.find(";");
      if (pos != -1) 
      {
          sub1 = sub.substr(0,pos);       
          sub2  = sub.substr(pos+1,pos);
          sub3  = sub.substr(pos+1,pos);
          sub4  =sub.substr(pos+1,pos);
          sub5  =sub.substr(pos+1,pos);       
          mnr   =stoi(sub1);
          stud.matrnr = mnr;
          stud.name = sub2;
          stud.vorname = sub3;
          stud.datum = sub4
          stud.note = float(sub5);
      }
      if (ch == '\n') 
      {
          stud = {matrn,name,vorname,datum,note};
          studArray.[i] = stud;
          i++;
      }


      putchar(ch);
    }   
    fclose (pFile);
    }


  return 0;
}

我试过 int mnr =stoi(sub1); 以及 int mnr = atoi(sub1); 其中 sub1 = "029383214"类似的东西......为什么它不起作用?编译器提示...

最佳答案

只需使用 std::stringstream :

int parse_int( const std::string& str )
{
    std::stringstream ss( str );
    int value;

    if( ss >> value )
        return value;
    else
        throw;
}

关于C++将int转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19728380/

相关文章:

c++ - 使用 g++ 连接两个具有相同函数签名的强函数符号的结果,为什么?

mysql - 在字符串中搜索字符串的 SQL 查询(但字符串可能是分开的)

c# - 格式化以下字符串的 Java 等价物是什么?

c++ - 结构对齐在 C 中编译正常,在 C++ 中失败

c++ - 如何从外部代码和 Makefile 启动 CodeBlocks 项目?

c++ - 使用Vector函数C++从文件中读取特定数据

c++ - 在 Visual Studio 2008 中的非托管 C++ 和托管 C# 项目中使用 C++ 代码

c++ - 如何立即停止/结束程序?

c++ - 确定没有 EXIF 数据的图像之间的停止差异

java - 任何人都可以解释一下 +(+i--)