C++ 遇到的问题小结

1. cannot convert 'std::basic_string<char>' to 'int' in assignment ...

原始code如下:  

 1                           int id2;
 2                           std::string label2;
 3                           std::string line;
 4 
 5                           while(getline(file, line)){
 6                             label2 = line.substr(5, line.size());
 7                             id2 = line.substr(1,4);
 8 
 9                             if (id2 == xxx)
10                                 break;
11                         }

提示错误:

cannot convert 'std::basic_string<char>' to 'int' in assignment ...

解决方法:

1                         while(getline(file, line)){
2                             label2 = line.substr(5, line.size());
3                             id2 = atoi((line.substr(1,4)).c_str());
4 
5                             if (id2 == xxx)
6                                 break;
7


参考网址:http://www.cplusplus.com/forum/general/13135/

2. stray "200" in program ...

如:

//                  cout << "vali_it->first" << vali_it->first << end;
                    cout<< "vali_it->first" << vali_it->first << end;

主要是因为输入法的问题,改成默认英文输入,不要涉及到中文输入法 ...

3. C++ 从string类型转换为int类型:

 方法一:在C标准库里面,使用atoi:

 

1  string text = '001';
2   int number = atoi( text.c_str() );

 方法二:在C++标准库里面,使用stringstream:(stringstream 可以用于各种数据类型之间的转换)
 

 1 #include <sstream>
 2 #include <string>
 3 
 4 std::string text = "152";
 5 int number;
 6 std::stringstream ss;
 7 
 8 ss << text;//可以是其他数据类型
 9 ss >> number; //string -> int
10 if (! ss.good())
11 {
12 //错误发生
13 }
14 
15 ss << number;// int->string
16 string str = ss.str();
17 if (! ss.good())
18 {
19 //错误发生
20 }
原文地址:https://www.cnblogs.com/wangxiaocvpr/p/4937524.html