[英]c++ ending loop with 'enter' hit
我需要通過按Enter鍵來結束輸入循環。 試圖找到一些東西,我在這里找一個人說下面的這段代碼可以工作,可惜的是沒有。 怎么了?
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int a = 0, h = 0, i=0;
string line;
int *tab=new int;
while (getline(cin, line) && line.length() > 0) // line not empty
{
stringstream linestr(line);
while (linestr >> a)// recommend better checking here. Look up std::strtol
{
tab[i]=a;
}
i++;
}
return 0;
}
去吧,謝謝!
這是代碼:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int a = 0, i=0;
string line;
getline(cin, line);
stringstream linestr(line);
int *tab = new int[line.size()/2+1];
while ( linestr >> a )
{
tab[i]=a;
i++;
}
for(int j=0; j<i; j++) cout<<tab[j]<<" ";
return 0;
}
問題
在代碼中,您會遇到分配問題,因為您為tab分配了一個整數。 因此,一旦您閱讀了第一個數字,您就會越界。 這是未定義的行為。
此外,您的while while循環播放直到輸入空行(無數字)為止。
解決方案
如果您要在一行上讀取幾個數字,則無需循環:
getline(cin, line);
stringstream linestr(line);
vector<int> tab;
while ( linestr >> a )
{
tab.push_back(a);
}
這種方法使用向量。 這樣的好處是,您不需要知道最后會有多少個數字。 然后,您可以使用tab.size()
找出向量的大小,並且可以完全像訪問數組一樣訪問單個元素。
其他解決方案(次優)
如果是學校,則不允許使用向量,則可以選擇次優替代品:
int *tab = new int[line.size()/2+1];
這將估計可能在字符串中的最大數字數(您肯定會更少)。
一種方法是使用以下方法,該方法讀取以空格分隔的數字並將它們放入向量中。
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
std::string line;
std::vector<int> v;
std::getline(std::cin, line);
std::stringstream sstream(line);
int i;
while (sstream >> i) {
v.push_back(i);
}
// Check your input vector.
/*
for(auto i : v){
std::cout << i << std::endl;
}
*/
}
輸入示例:
32 22 62 723765 26 62 72 7 -5 7 2 7 152 62 6 262 72
代碼中的問題是您分配了足夠的空間來容納一個int
int *tab=new int;
並且正在使用tab
,好像它可以容納所需的int
一樣多。
如果允許使用std::vector
,則將上面的行更改為:
std::vector<int> tab;
和使用
while (getline(cin, line) && line.length() > 0) // line not empty
{
stringstream linestr(line);
while (linestr >> a)
{
tab.push_back(a);
}
}
如果不允許使用std::vector
,則必須弄清楚如何處理tab
的動態性質。 為了快速解決,可以使用靜態定義的數組,並在耗盡數組容量后立即停止讀取。
int const MAX_ELEMENTS = 100;
int tab[MAX_ELEMENTS];
...
while (getline(cin, line) && line.length() > 0 && i < MAX_ELEMENTS)
{
stringstream linestr(line);
while (linestr >> a)
{
tab[i] = a;
++i; // Needs to be here not outside this loop.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.