Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从没有正则表达式的字符串解析int?_C++_String_C++11 - Fatal编程技术网

C++ 从没有正则表达式的字符串解析int?

C++ 从没有正则表达式的字符串解析int?,c++,string,c++11,C++,String,C++11,如果我有一个字符串,其中有一些单词和一些数字,比如文本125,那么不使用正则表达式就可以得到这个数字并将其转换为int吗?是的,如果您知道它是一个单词后跟一个数字,那么可以使用stringstream std::stringstream ss("Text 125"); std::string buffer; //a buffer to read "Text" into int n; //to store the number in ss >> buffer >> n;

如果我有一个字符串,其中有一些单词和一些数字,比如文本125,那么不使用正则表达式就可以得到这个数字并将其转换为int吗?

是的,如果您知道它是一个单词后跟一个数字,那么可以使用stringstream

std::stringstream ss("Text 125"); 
std::string buffer; //a buffer to read "Text" into
int n; //to store the number in

ss >> buffer >> n; //reads "Text" into buffer and puts the number in n
std::cout << n << "\n";
是的,如果您知道字符串流是一个单词后跟一个数字,那么您可以使用它

std::stringstream ss("Text 125"); 
std::string buffer; //a buffer to read "Text" into
int n; //to store the number in

ss >> buffer >> n; //reads "Text" into buffer and puts the number in n
std::cout << n << "\n";
如果您确切知道所需字符串的格式,即

总是以文本开始 后面跟着一个空格 后面跟着一个数字 然后结束 所以在正则表达式中,它是/^Text\d+$/ 您可以组合std::find和std::substr

然而,这只适用于这些特定情况。即使/^Text\d+$/是唯一的预期格式,其他输入字符串也可能存在,因此您需要添加适当的长度检查,然后抛出异常或返回无效数字,或者针对无效输入字符串执行任何需要执行的操作

@DanielGiger的答案更为普遍。它只要求数字是第二个字符串,如果您确切知道所需字符串的格式,即它是

总是以文本开始 后面跟着一个空格 后面跟着一个数字 然后结束 所以在正则表达式中,它是/^Text\d+$/ 您可以组合std::find和std::substr

然而,这只适用于这些特定情况。即使/^Text\d+$/是唯一的预期格式,其他输入字符串也可能存在,因此您需要添加适当的长度检查,然后抛出异常或返回无效数字,或者针对无效输入字符串执行任何需要执行的操作


@DanielGiger的答案更为普遍。它只要求数字是第二个字符串,涵盖了更一般的情况/^\S+\S+\d+/

谢谢您的回答!可惜我不会写ss>>字符串>>n;因为我在任何地方都不需要那根绳子谢谢你的回答!可惜我不会写ss>>字符串>>n;因为我哪里都不需要那根绳子
  const std::string inputStr = "Text 125";
  const std::string textStr = "Text ";

  const std::size_t textPos = inputStr.find(textStr);
  const std::size_t numberPos = textPos + textStr.length();
  const std::string numberStr = inputStr.substr(numberPos);
  const int numberInt = std::atoi(numberStr.c_str());