涉及循环的简单程序由于某种原因卡住
Simple program involving a loop getting stuck for some reason
当我输入输入字符串时,程序卡住了。 我已经测试了程序中的所有其他分支,所以问题就在这里。
注意:无限循环是有意的,应该通过 break 语句来打破。
for (i = 0 ; i >= 0 ; i++)
{
text.append("kk");
if ((text.find("." , j)) < 0 )
{
text.erase(text.size() - 2, 2);
text2.append(text);
writer << text2 << endl;
text2.clear();
j = 0;
break;
}
else
{
j = text.find("." , j) + 1;
k = j + 1;
letter = static_cast <int> ( text.at(k) );
if (( letter < 123 ) && ( letter > 96 ))
{
letter = (letter - 32);
(text.at(k)) = static_cast <char> (letter);
text.erase(text.size() - 1, 2);
}
else
{
text.erase(text.size() - 1, 2);
}
}
}
正如其他人已经指出的那样,你有一个无限循环。我通常会看到以下格式的字符串查找循环。
int found = 0;
while ((found = text.find(".", found )) != string::npos) {
//...
}
这是因为您永远不会擦除.
,因此您永远不会输入第一个if
条件(带有中断的条件)。
你的逻辑是这样的:
Append "kk" to the string
If you don't find a '.'
exit
Else
If the second letter after the '.' is lower case
Change it to upper case
Delete the last letter in the string
Else
Delete the last letter in the string
然后你再次循环
假设您的字符串是:zzz.abcd您的迭代将是:
zzz.aBcdk
zzz.aBcdkk
zzz.aBcdkkk
等。。
这是造成最大伤害的线路:
j = text.find("." , j) + 1;
在这里,如果您没有找到".",则将 j 设置为 0 (-1 + 1),因此在下一次迭代中,您将再次执行完全相同的搜索。
编辑:没关系,我的答案是错误的。我不知道 std::npos 是一个常量设置为 -1。
该行: if ((text.find("." , j)) < 0 )
永远不会是真的,所以中断永远不会被执行。
如果未找到文本,std::string.find()
将返回 std::npos
,而不是小于 0 的值。
参见: std::string.find()
我知道你想坚持你的代码,但是,这真的很糟糕,我讨厌你学习坏习惯。
有时,甚至大多数时候,我们作为开发人员必须能够从代码示例中学习。我知道你不想使用任何你不理解的代码结构。但是,在大学和工作中,您将不得不从您不理解的代码中学习。这是提高技能和知识的好方法。
我写了一些代码来解决你的问题。这可能不是最好的解决方案。它经过测试并有效。请查看此代码并询问您是否不了解任何内容。希望这对您有价值。
#include <string>
#include <cctype>
void ToUpper( std::string& text, int position );
void ToUpper( std::string& text, int position )
{
char c;
c = text.at(position);
text.at(position) = std::toupper(c);
return;
}
int main(int argc, char *argv[])
{
std::string text = "this is. a very simple. example. ok.";
int found = 0;
//Handle first character of sentence
if ((found = text.find_first_not_of(" ", 0)) != std::string::npos)
{
ToUpper( text, found );
}
while ((found = text.find(".", found )) != std::string::npos)
{
found = text.find_first_not_of(" .", found);
if( found != std::string::npos )
{
ToUpper( text, found );
}
}
return 0;
}
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 由于某种原因,WriteProcessMemory无法正常工作
- 我有一个应该打印数组的函数,但由于某种原因它不起作用
- 在矩阵逆变器上工作,由于某种原因,我的指数循环不起作用
- 由于某种原因,我的代码中出现了 [json.exception.type_error.302]。我知道错误意味着什么,但我不知道哪里有故障
- 由于某种原因,客户端未调用服务器 RPC
- 由于某种原因,我无法创建 GLFW 上下文
- 由于某种原因,多维数组不会从函数中更改元素
- 由于某种原因,用浮子的乘法是错误的
- "total += i;"由于某种原因不起作用
- C++ 由于某种原因,我无法让模板在链表中工作,我敢打赌这是一个简单的错误,但我就是不明白
- 我是初学者,由于某种原因,这不起作用,我正在使用视觉工作室
- C++:当我输入一个字符串时,由于某种原因,程序期望更多,并导致整个代码出现问题
- 由于某种原因,FSTREAM测试程序崩溃
- XNextEvent 由于某种原因不起作用
- 由于某种原因,必须发送两次 MPI 消息
- 由于某种原因,使用 OR 运算符执行操作不起作用
- 涉及循环的简单程序由于某种原因卡住
- 程序由于某种原因挂起
- 简单的程序由于某种原因而崩溃