gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:31:08 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com