[英]Inputting numbers separated by spaces
我正在嘗試為在線編碼平台上的問題之一編寫代碼。 我已經編寫了代碼,但是無法獲得所需格式的輸入。 我需要輸入一個具有三個整數(例如n1,n2和m)的輸入。 問題是輸入可以是由空格分隔的數字。 我嘗試尋求幫助,甚至找到了一種方法,但是它沒有用。
這是我的代碼:
#include <string>
#include <ctype.h>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
int main()
{
int t;
cout << "Enter the number of test cases" << endl;
cin >> t;
do
{
string rawInput;
int isNum, n1, n2, m, t, i, j;
int arr[3];
arr[0] = 0;
arr[1] = 0;
arr[2] = 0;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while (getline(cin, rawInput))
{
cout << "Rawinput" << rawInput.length();
for (i = 0; i < rawInput.length(); ++i)
{
cout << rawInput[i];
}
int j = 0, k = 0;
for (int j; j < rawInput.length(); ++j)
{
isNum = isdigit(rawInput[j]);
if (isNum)
{
arr[k] = arr[k] * 10 + atoi(rawInput[j]);
}
else
k = k++;
}
cout << "I am Array" << endl;
for (int l = 0; l < 3; l++)
cout << arr[l] << endl;
}
if (arr[0] >= arr[2] && arr[1] >= arr[2])
{
for (int i = 1; i <= arr[2]; i++)
{
if (arr[0] >= i && arr[1] >= i)
{
arr[0] = arr[0] - i;
arr[1] = arr[1] - i;
}
}
}
cout << arr[1] + arr[0];
t--;
} while (t > 0);
}
具體來說,函數atoi似乎不起作用。 我嘗試使用stoi,但即使這樣也不起作用。
如果您只是想收集一系列用空格分隔的整數作為用戶輸入,即1 2 3 4 5
,則不必使用getline
方法。
您可以針對以下情況重做while
循環:
int input;
while (cin >> input)
{
<<HANDLE INPUT>>
}
這將大大減少您要執行的行解析,並且只要有一個取整,它將捕獲該行上的下一個輸入整數。 上面的相同系列的循環迭代將像這樣...
Loop # Input Taken
1 1
2 2
3 3
... ...
這樣就無需解析,因為它將在每次迭代中處理一個整數輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.