将字符串(以char*形式给出)解析为int的C++方式是什么?强大而清晰的错误处理是一个优点(而不是返回零).
可能重复:
如何在C++中将字符串解析为int?
如何将C++字符串转换为int?
假设您希望字符串中包含实际数字(例如,"1","345","38944").
另外,让我们假设你没有提升,你真的想用C++方式来做,而不是狡猾的旧C方式.
我有一个程序,它逐行读取文件的内容,将每一行存储到字符串向量中,然后打印向量的内容。
\n\n将文件数据读入字符串向量后,我尝试将每一行string从uint32. 文件的每一行都由32-bit数字组成。输入数据文件的示例(input_file.dat):
31401402\n67662718\n74620743\n54690001\n14530874\n13263047\n84662943\n09732679\n13839873\nRun Code Online (Sandbox Code Playgroud)\n\n我想将这些字符串中的每一个转换为uint32_t, 对于我编写的另一个程序,该程序将这些数字转换为 ASCII 格式(该程序需要用于uint32_t转换)。
到目前为止我的计划:
\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\n/*\n * Program to iterate through all lines in file and put them in given vector\n *\n */\nbool getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)\n{\n\n // Open the File\n std::ifstream in(fileName.c_str());\n\n // Check if object is valid\n if(!in)\n {\n std::cerr << "Cannot open the File : "<<fileName<<std::endl;\n return false;\n }\n\n std::string …Run Code Online (Sandbox Code Playgroud) 我得到了一个字符串y,其中我确保它只包含数字.在使用stoi函数将其存储在int变量中之前,如何检查它是否超出整数的边界?
string y = "2323298347293874928374927392374924"
int x = stoi(y); // The program gets aborted when I execute this as it exceeds the bounds
// of int. How do I check the bounds before I store it?
Run Code Online (Sandbox Code Playgroud) 如果我使用>>运算符读取istream中的整数,并且表示的整数大于INT_MAX,则操作只返回INT_MAX.
我目前正在对INT_MAX进行比较以检测溢出,但如果操作输入"2147483647",则它将返回错误,而实际上没有,结果有效.
#include <iostream>
#include <sstream>
#include <climits>
int main() {
std::istringstream st("1234567890123"); // Try with 2147483647
int result;
st >> result;
if (result == INT_MAX)
std::cout << "Overflow!" << std::endl;
else
std::cout << result << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是什么意识形态正确的方法?