在 C++ 中输入一个或多个特定字符串 has/have 之前,如何将输入存储为字符串?
How to store input as a string until one or more specific string(s) has/have been entered in C++?
这是我在该网站上的第一个条目,目前我是一名大学学生,正在学习 C++。在给定的作业中,我遇到了一个问题并一直试图解决它但找不到完整的解决方案。简而言之,我需要输入直到读到“END”或“end”这个词。
例如;
Enter source string: there are good times
and there are bad times
END
Enter search string: are+
...继续
问题是我使用了cin.getline()
函数(我稍后会展示),但我无法同时控制“END”和“end”。 cin.getline()
函数只检查一个。
这是我的一段代码;
#define MAX_TARGET_LENGTH 500
char target[MAX_TARGET_LENGTH];
cout << "Enter source string: ";
cin.getline (target, MAX_TARGET_LENGTH, 'END');
如您所见,我需要让它检查“END”或“end”,以先到者为准。
是否有任何方法或任何其他功能可以使它 运行 成为它应该的样子?
感谢您的关注,如果我输入的问题在某些方面令人困惑或错误,抱歉。
我想出了以下解决方案:
#include <iostream>
#include <vector>
using namespace std;
#define MAX_TARGET_LENGTH 500
int main() {
char target[MAX_TARGET_LENGTH];
while(true)
{
cout << "Enter source string: ";
while(true)
{
cin.getline (target, MAX_TARGET_LENGTH);
std::string line = target;
if(line.compare("end") == 0 || line.compare("END") == 0)
{
break;
}
}
}
return 0;
}
我正在使用Stringclass解决问题
Strings are objects that represent sequences of characters.
并且它们具有有用的功能。其中之一是功能“比较”。有了它,您可以检查一个字符串是否等于另一个字符串。如果字符串相同,该函数将 return 0。否则它将 return 1 或 -1(更多信息 here)。
内部 while 循环中的主要内容。
while(true)
让 while 循环永远持续下去。
你得到一个新的输入行
cin.getline (target, MAX_TARGET_LENGTH);
您将其存储在变量目标中。然后你可以将“目标”变成一个字符串
std::string line = target;
因为,类型是兼容的。然后 if 语句检查“end”或“END”的输入。
if(line.compare("end") == 0 || line.compare("END") == 0)
{
break;
}
如果其中一个或两个语句为真,“break”将退出内部 while 循环并使程序再次打印“Enter source string:”。
这是我在该网站上的第一个条目,目前我是一名大学学生,正在学习 C++。在给定的作业中,我遇到了一个问题并一直试图解决它但找不到完整的解决方案。简而言之,我需要输入直到读到“END”或“end”这个词。 例如;
Enter source string: there are good times
and there are bad times
END
Enter search string: are+
...继续
问题是我使用了cin.getline()
函数(我稍后会展示),但我无法同时控制“END”和“end”。 cin.getline()
函数只检查一个。
这是我的一段代码;
#define MAX_TARGET_LENGTH 500
char target[MAX_TARGET_LENGTH];
cout << "Enter source string: ";
cin.getline (target, MAX_TARGET_LENGTH, 'END');
如您所见,我需要让它检查“END”或“end”,以先到者为准。
是否有任何方法或任何其他功能可以使它 运行 成为它应该的样子?
感谢您的关注,如果我输入的问题在某些方面令人困惑或错误,抱歉。
我想出了以下解决方案:
#include <iostream>
#include <vector>
using namespace std;
#define MAX_TARGET_LENGTH 500
int main() {
char target[MAX_TARGET_LENGTH];
while(true)
{
cout << "Enter source string: ";
while(true)
{
cin.getline (target, MAX_TARGET_LENGTH);
std::string line = target;
if(line.compare("end") == 0 || line.compare("END") == 0)
{
break;
}
}
}
return 0;
}
我正在使用Stringclass解决问题
Strings are objects that represent sequences of characters.
并且它们具有有用的功能。其中之一是功能“比较”。有了它,您可以检查一个字符串是否等于另一个字符串。如果字符串相同,该函数将 return 0。否则它将 return 1 或 -1(更多信息 here)。
内部 while 循环中的主要内容。
while(true)
让 while 循环永远持续下去。
你得到一个新的输入行
cin.getline (target, MAX_TARGET_LENGTH);
您将其存储在变量目标中。然后你可以将“目标”变成一个字符串
std::string line = target;
因为,类型是兼容的。然后 if 语句检查“end”或“END”的输入。
if(line.compare("end") == 0 || line.compare("END") == 0)
{
break;
}
如果其中一个或两个语句为真,“break”将退出内部 while 循环并使程序再次打印“Enter source string:”。