मैं उपयोगकर्ता इनपुट हैंडलिंग का अभ्यास कर रहा हूं। मेरा लक्ष्य है कि उपयोगकर्ता अंतरिक्ष ("") से अलग पूर्णांक की एक पंक्ति दर्ज करें, उन्हें पूर्णांक के रूप में पढ़ें, उन्हें स्टोर करें और बाद में उन पर काम करें। मैं एक दिलचस्प समस्या (मेरे विरोध में कम से कम) जिस तरह से कर रहा हूं, उस पर ठोकर खाई, ऐसा लगता है कि यह हमेशा उपयोगकर्ता द्वारा दर्ज किया गया अंतिम अंक नहीं पढ़ रहा है। मैं यहां पूरा कार्यक्रम पोस्ट करूंगा (क्योंकि इसमें कुछ अतिरिक्त लिबर्री शामिल हैं)। मैं, कार्यक्रमएक स्ट्रिंग को ठीक से नहीं पढ़ रहा
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;
int main()
{
//this vector will store the integers
vector<int> a;
// this will store the user input
string inp;
getline(cin, inp);
// this string will temporarily store the digits
string tmp;
//be sure that the reading part is okay
cout << inp << endl;
//until you meet something different than a digit, read char by char and add to string
for(int i = 0; i < inp.length(); i++)
{
if(isdigit(inp[i]))
{
tmp +=inp[i];
}
else
{
// when it is not a character, turn to integer, empty string
int value = atoi(tmp.c_str());
a.push_back(value);
tmp = "";
}
}
// paste the entire vector of integers
for(int i = 0; i < a.size(); i++)
{
cout << a[i] << endl;
}
return 0;
}
कुछ उदाहरण इनपुट के लिए द्वारा
for(int i = 0; i <inp.length(); i++)
, अपने अपेक्षित आउटपुट क्या है, और क्या आप वास्तव में देखते हैं? – BoBTFish
यदि मैं "25 30 46" इनपुट करता हूं तो मुझे वेक्टर में 25 और 30 मिलेंगे, हालांकि स्ट्रिंग में "25 30 46" – Bloodcount
आह होगा, मैंने देखा कि आपका मतलब सिर्फ एक लापता अंक था। – BoBTFish