2012-10-13 31 views
1

我一直在处理一个问题,在这个问题中,我需要分隔空间输入(< = 10),然后是两个独立数组中的下一行中的其他空间分隔输入在CPP中,我在cpp中使用了getline函数。我正面临的问题是输入输入的最后一行。我无法弄清楚我面临的是什么问题。最后一行出现时,输出停止并等待我输入一些东西后,它提供了output.Here是我的代码..输入空间在cpp中使用getline的数组中分隔的数字

while(test--) 
{ 

    int len[100]; 
    int pos[100]; 


    string a,b,code; 
     // int t=1; 


    cin>>code; 


    cin.ignore();//ignores the next cin and waits till a is not input 


    getline(cin,a); 


    // deque<char> code1; 

    // code1.assign(code.begin(),code.end()); 




    int k=0; 
    int t=a.length(); 
    for(int i=0;i<t/2+1;i++)//converts two n length arrays pos[] and len[] 
    { 

     scanf("%d",&len[i]); 

    while(a[k]==' ') 
    { 
     k++; 

    } 




      pos[i]=a[k]-48; 
      k++; 
       } 



     //int c;} 

`

+1

好的!你正在使用空间分隔的输入。但是在此之后你想要做什么? 意图目前还不清楚,代码看起来有点模糊。 – sjsam

+0

看起来他可能是C++的新手。很多事情在这里都出错了。 –

+0

@Geoff_Montee:嗯。但没有担心,因为我们在那里帮助.. – sjsam

回答

1

你的代码是混乱的,并且不看起来应该起作用。您正在使用cin/scanf进行阻止输入,因此如果标准输入上没有准备好输入,则它正常等待您。

这是它看起来像你试图做:

  • 读入行成使用getline称为a的字符串。
  • 使用scanf将数据从a读入阵列。

但是,scanf不是为此制作的。 scanf函数从键盘输入。我想你想用sscanf来输入字符串a的值。

但更好的是使用stringstreams

起初我还以为你想读的命令行输入的长度,所以我建议这样的:

size_t arr_len; 

cin >> arr_len; 

if (cin.fail()) 
{ 
    cerr << "Input error getting length" << endl; 
    exit(1); 
} 

int* len = new int[arr_len]; 
int* pos = new int[arr_len]; 

for (int count = 0; count < arr_len; count++) 
{ 
    cin >> len[count]; 

    if (cin.fail()) 
    { 
     cerr << "Input error on value number " << count << " of len" << endl; 
     exit(1); 
    }   
} 


for (int count = 0; count < arr_len; count++) 
{ 
    cin >> pos[count]; 

    if (cin.fail()) 
    { 
     cerr << "Input error on value number " << count << " of pos" << endl; 
     exit(1); 
    } 
} 

delete [] pos; 
delete [] len; 

然后我看着更加谨慎。看起来这是你想要做的。我使用的是std::vector而不是int[],但是如果您真的想要,就不难改变它。

string line; 

getline(cin, line); 

if (cin.fail()) 
{ 
    cout << "Failure reading first line" << endl; 
    exit(1); 
} 

istringstream iss; 

iss.str(line); 

vector<int> len; 

size_t elements = 0; 

while (!iss.eof()) 
{ 
    int num; 
    iss >> num; 

    elements++; 

    if (iss.fail()) 
    { 
     cerr << "Error reading element number " << elements << " in len array" << endl; 
    } 

    len.push_back(num); 
} 

getline(cin, line); 

if (cin.fail()) 
{ 
    cout << "Failure reading second line" << endl; 
    exit(1); 
} 

iss.clear(); 
iss.str(line); 

vector<int> pos; 

elements = 0; 

while (!iss.eof()) 
{ 
    int num; 
    iss >> num; 

    elements++; 

    if (iss.fail()) 
    { 
     cerr << "Error reading element number " << elements << " in pos array" << endl; 
    } 

    pos.push_back(num); 
} 
+0

什么是downvote?我很难弄清楚OP在做什么,但仍然根据他可能想做的事情提供了一些潜在的解决方案。 –

相关问题