检查字符串是否以(%i)结尾,然后将该数字赋给一个变量
Check if string ends with (%i) then assign that number in a variable
假设我有一个字符串"MyName(10)"
我想检查以(%i)
结尾的字符串,并在变量中分配该数字。
我试过sscanf
,但它不起作用。
sscanf("MyName(10), "%s(%i)", tempName, &count);
tempName
和count
中MyName(10)
的存储为0
。
MyName
可以是可变长度,它不是固定的"MyName"
,它可以是"Mynaaaaaame"
。
试试这个示例代码。也许这能帮上忙……你可以根据你的需要做任何调整
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define IS_DIGIT(x)
( x == '0' || x == '1' || x == '2' ||
x == '3' || x == '4' || x == '5' || x == '6' ||
x == '7' || x == '8' || x == '9' )
/* the function will return 0 in success and -1 in error */
/* on success num will contain the pointer to the number */
int
check_last_num(char * str , int * num)
{
int len = strlen(str);
int index = len - 1;
/* make sure the last char is ')' */
if (str[index] != ')')
return -1;
while ( --index >= 0 && (str[index] != '(') ) {
char c = str[index];
if ( ! IS_DIGIT(c) )
return -1;
}
/* loop exit check */
if (index < 0)
return -1;
*num = atoi((const char *) &str[index + 1]);
return 0;
}
int main(int argc , char *argv[] )
{
int rc ;
if ( 0 == check_last_num("MyName(890790)" , & rc))
printf ("%d n" , rc);
else
printf ("error n");
return 0;
}
sscanf(Name, "%*[^(]%c%i%[^)]%*c", &var);
由于这被标记为c++,您可以这样做:
void assignVariable(std::string& s, std::string replace, int value)
{
std::size_t pos;
while ((pos = s.find(replace)) != std::string::npos)
s.replace(pos, 2, std::to_string(value));
}
int main()
{
std::string name = "%imyname(%i)%i";
assignVariable(name, "%i", 365);
std::cout << name;
cin.get();
return 0;
}
这将替换传递给函数的字符串中出现的所有replace。如果你想把它限制在最后一次出现,你可以使用std::string::find_last_of()
相关文章:
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 使用指针选择长无符号变量中的数字
- 如果静态变量只为程序的整个部分存储了一个副本,为什么我不能使用静态变量交换 2 个数字?
- 如何使用C++中不是文字的变量在数字中显示单引号和两个引号?假设 6'2" 英尺
- 常量整数变量和数字的不同类型推导
- 运行时检查失败 #2 - 变量"数字选择"周围的堆栈已损坏
- 在 c++ 中向数组变量添加一个数字
- 在Visual Studio中生成的匿名命名空间变量的损坏名称的数字部分是什么意思
- 为什么 al_draw_textf() 打印数字而不是存储在字符串变量中的字母
- 使用模量来找出数字是否可以除去不起作用的变量
- 如何判断变量是否是一个复杂的数字C
- 在 c++ 中不能将超过 10 位数字放入一个变量中
- 使用单个数字表示多个变量
- 如何在变量中仅允许数字
- 如何使用同一变量输入字母和数字?(C )
- 打印长双变量的所有十进制数字
- 尝试将数字放入 ifstream 文件中的变量中
- 如何调用一个变量(包含rand()函数)并得到不同的数字
- 为循环嵌套的变量快速生成数字组合
- 如何在C++中显示数字变量