[英]Is there a way to make C++ take in an undefined number of strings from cin?
我試圖讓用戶輸入相當數量的單詞(大約 10-20)然后解析輸入,但是使用下面的代碼將等到用戶為每個字符串輸入一個值。
有沒有辦法讓 C++ 自動用 null 字符或類似字符填充剩余的字符串,這樣輸入的單詞數小於最大值不會導致阻塞?
代碼:
#include <iostream>
#include <string>
int main()
{
std::string test1;
std::string test2;
std::string test3;
std::cout << "Enter values\n:";
std::cin >> test1 >> test2 >> test3;
std::cout << "test1: " << test1 << " test2: " << test2 << " test3: " << test3 << std::endl;
}
要讀取(和存儲)未知數量的空格分隔字符串,您需要存儲每個字符串。 以靈活的方式提供存儲的最基本方法可以無限添加(直到您的可用 memory 限制)是使用字符串向量。 字符串為每個字符串提供存儲空間,而向量容器提供了一種將任意數量的字符串收集在一起的簡單方法。
您的字符串向量( vs
)可以聲明為:
#include <iostream>
#include <string>
#include <vector>
...
std::vector<std::string>vs {};
std::vector提供.push_back()
成員 function 以將元素(在本例中為string
)添加到向量,例如
std::vector<std::string>vs {};
std::string s;
while (std::cin >> s)
vs.push_back(s);
它只是讀取字符串s
直到遇到EOF
,並且使用vs.push_back(s);
.
總而言之,您可以這樣做:
#include <iostream>
#include <string>
#include <vector>
int main (void) {
std::vector<std::string>vs {};
std::string s;
while (std::cin >> s) /* read each string into s */
vs.push_back(s); /* add s to vector of strings */
for (auto& w : vs) /* output each word using range-based loop */
std::cout << w << "\n";
}
示例使用/輸出
$ echo "my dog has fleas" | ./bin/readcintostrings
my
dog
has
fleas
如果您還有其他問題,請仔細查看並告訴我。
你可以使用while循環。像這樣的東西
string s;
while (cin >> s) {
cout << s << endl;
}
或者取一個字符串向量並進行一段時間,在 while 循環中獲取輸入並將它們推入向量中。
如您所見,它不存儲。 如果你想存儲。 做
vector<string>text;
while(cin>>s){
text.push_back(s);}
我用這段代碼弄清楚了:
#include <iostream>
#include <string>
int main()
{
std::string testTemp;
std::string brokenUp[20];
int lastOne = 0;
std::cout << "Enter values\n:";
std::getline(std::cin, testTemp);
for(int current = 0; !testTemp.empty() && testTemp.find(' ') != -1; current++)
{
brokenUp[current] = testTemp.substr(0, testTemp.find(' '));
testTemp.erase(0, testTemp.find(' ') + 1);
lastOne = current;
}
lastOne++;
brokenUp[lastOne] = testTemp;
//this next part is just a test
for(int i = 0; i <= lastOne; i++)
{
std::cout << brokenUp[i] << std::endl;
}
}
但是您可以使用任何東西作為分解字符串的存儲(即列表或動態數組)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.