c++ - 如何提取字符串中任意位置的下一个整数?

标签 c++ string stream cin getline

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

I n
//where n is any integer representing the line number.

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

例如:

D 16 // deletes line 16
I 9 // Inserts string at line 9
L // lists all lines

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

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.

关于c++ - 如何提取字符串中任意位置的下一个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28975325/

相关文章:

c++ - 如何使这个 C++ 对象不可复制?

java - 在 Java 中从另一个类创建数组对象

java - 无法从 List<Functions.Function1<Object,String>> 转换为 List<String> 使用 Selenium 和 Stream() Java8 从 WebElements 列表创建列表

php - 什么设置(ab)使用node.js作为超快速轮询和ajax服务器来更新数据库(类似于Google Spreadsheet方法)

ruby - 正则表达式匹配 string1,除非前面有 string2

video - 在软件中解码曼彻斯特双相标记(代表 SMPTE 时间码音频流)

c++ - C++ 中有 128 位整数吗?

c++ - 避免从函数返回时复制 - 不依赖编译器优化

c++ - 错误 : forward declaration of ‘class SActionPrivate’ when using PIMPL

javascript - 为什么这种方法不能在 JavaScript 中分配字符?