如何在字符串中的任意位置提取下一个整数

How to extract next integer in an arbitrary position in string?

本文关键字:位置 提取 下一个 整数 任意 字符串      更新时间:2023-10-16

我的代码在下面,我正在研究一个简单的文本编辑器。用户需要能够输入以下格式:

我 n
其中 n 是表示行号的任何整数。

我在下面使用了 switch 语句来查看他们键入的第一个字符是什么,但在情况"I"(插入)和情况"D"(删除)的情况下,我需要能够提取他们之后键入的整数。

例如:

D 16/

/删除第 16
行 I 9//在第 9
行插入字符串 L//列出所有行

我已经尝试了一些不同的事情,但没有一个顺利,所以我想知道是否有更好的方法来做到这一点。

void handle_choice(string &choice)
{   
    int line_number;
      // switch statement according to the first character in string choice.
    switch (choice[0]) 
    {
    case 'I':
       // code here to extract next integer in the string choice
      break;
    case 'D':
      break;
    case 'L':
      break;
    case 'Q':
      break;
    default:
      break;
    }

我尝试了一些不同的东西,如getline()和cin <<但是如果用户没有以该特定格式输入行,我无法使其正常工作,我想知道是否有办法。

谢谢。

#include <cctype>
#include <string>
using namespace std;
// This function takes the whole input string as input, and
// returns the first integer within that string as a string.
string first_integer(string input) {
   // The digits of the number will be added to the string
   // return_value. If no digits are found, return_value will
   // remain empty.
   string return_value;
   // This indicates that no digits have been found yet.
   // So long as no digits have been found, it's okay
   // if we run into non-digits.
   bool in_number = false;
   // This for statement iterates over the whole input string.
   // Within the for loop, *ix is the character from the string
   // currently being considered. 
   for(string::iterator ix = input.begin(); ix != input.end(); ix++) {
     // Check if the character is a digit.
     if(isdigit(*ix)) {
         // If it is, append it to the return_value. 
         return_value.push_back(*ix);
         in_number = true;
     } else if(in_number) {
         // If a digit has been found and then we find a non-digit
         // later, that's the end of the number.
         return return_value;
     }
   }
   // This is reached if there are no non-digit characters after
   // the number, or if there are no digits in the string. 
   return return_value;
}

在 switch 语句中,您将像这样使用它:

case 'I':
     string number = first_integer(choice);
     // Convert the string to an int here.

你不需要定义一个函数,我会做这样的事情:

char command; 
int line; 
cin >> command >> line; //put the first character in command, and the next one in line

如果确实要使用函数,则应将字符串转换为字符串流。字符串流允许您像 cin 一样为变量赋值,处理所有转换,在输入失败时通知您,并跳过空格。

所以在你的函数中,你将首先创建一个字符串流

stringstream inputStream (choice); //make a stringstream from the input string

接下来,将字符串流值输入到变量中,如下所示:

char command; 
int line; 
inputStream >> command >> line;

现在,命令包含字母,行包含数字。但是,有时没有行号,只有命令。在这种情况下,第二个输入将失败。方便的是,字符串流允许您检查以下内容:

inputStream >> command >> line; 
if(inputStream.fail()) { //input to line failed, probably because there was no number
/*your code for when there is no number*/
}

您可能需要包括其他检查。