试图在字符串中找到一个数字,更改它,放回并找到下一个数字

Trying to find a number in a string, change it, put it back and find the next number

本文关键字:数字 下一个 字符串 一个      更新时间:2023-10-16

如果这个问题已经得到回答,我很抱歉。如果是,请告诉我解决方案。

我目前正在尝试遍历一个文本文件,对其进行迭代以找到一个数值,并将该值管道传输到子/父进程中,然后在那里将更新后的值返回到文本中。尽管很简单,我还是试图找到数字,然后将它们放入一个数组/字符串中,这样我就可以将其输入到管道中,然后将其反馈到文本中。我已经做了5天了,所以我终于向你们寻求帮助了。再次,如果这种情况已经存在,请道歉。

我目前正在浏览文本,并检查每个字符是否为整数。我可以把它放进一根绳子里,但它只是一根长长的大绳子。我不知道如何实现它。

这就是我到目前为止所拥有的。

while(!readText.eof())
{
while(getline(readText, item))
{
readText >> item;
for(int i=0; i < item.length(); ++i){
if(isdigit(item[i])) //checking if it is a digit
newitem += item[i]; //puts into string
if(!isdigit(item[i])) // if it's not a digit feed it out (but maybe I 
//should put into new variable?
cout << item[i];
else if(isspace(item[i]))//keeps the spaces as cout, but again, maybe 
//put it into a variable?
cout << " ";
}
}
}

我面临的挑战是试图弄清楚如何将这些价值观分开并放回原处。我会随着指数的增长而增长,但数字会增长,所以位置不会那么准确。


更新的上下文

感谢大家的帮助。一个示例文件是

In the b6765lue sky there are 59 clouds. The gra7ss is green 766 and it 837 has 7 a cow in i87t.

我需要通过一个过程/函数来更改数字。就像你提到的,数字的大小自然会变大。测试文件可以是100行。

In the b6789lue sky there are 83 clouds. The gra31ss is green 790 and it 861 has 31 a cow in i111t.

这些值已随5个过程和增量值5进行了更改。

如果到达起始位置,为什么不保存一个值和一个新值的起始位置以进行打印?所以,在我看来:

struct replace_integer
{
int old_int_length;
int new_int_value;
int int_to_replace_text_position;
};

然后,当你打印下来的时候,跳过旧的int,打印新的。它行得通吗?

要记住起始位置,您应该修改您的周期:

int item_length = item.length();
for(int i=0; i < item_length ; ++i)
{
if(isdigit(item[i]))
{
int_to_replace_text_position = i;
while(isdigit(item[i++]) && i < item_length )
newitem += item[old_int_length_counter]; //puts into string
old_int_length = i - int_to_replace_text_position; //check it, i may have a 1 position mistake, too sleepy, so I can lose "-1"
}
if(!isdigit(item[i])) // if it's not a digit feed it out (but maybe I 
//should put into new variable?
cout << item[i];
else if(isspace(item[i]))//keeps the spaces as cout, but again, maybe 
//put it into a variable?
cout << " ";
}