0
我寫,我會給出一個字符串,如程序:C++在一個漫長的字符串的字符串轉換爲整數
5,6,10
和我做了一個程序,它數字5 6 10(忽略逗號)並將它們放入矢量中。 與我的程序唯一的問題是,如果我這樣做
5,6,F
它會變成使得f爲0。而我想,如果它認爲該計劃只是報告錯誤除0之外的任何東西0 1 2 3 4 5 6 7 8 9,
我該如何修復我的程序來做到這一點?這裏是我的代碼:
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str, temp;
cout << "enter string: \n";
getline (cin, str);
vector<int> vec;
int num;
for (int j=0; j < str.size(); j++)
{
int num2= str.size()-1;
if (isdigit(str[j]))
{
temp+= str[j];
num = atoi(temp.c_str());
if (num2 ==j) //if program is at end of string and it's still a number
vec.push_back(num); //push back value
}
else if (str[j] == ',')
{
num = atoi(temp.c_str());
temp.clear();
vec.push_back(num);
}
else
{
cout << "error\n";
temp.clear();
}
}
for (int k=0; k < vec.size(); k++)
cout << vec[k] <<endl;
}
我有我的程序執行strtol時遇到麻煩。我通讀了cpp對它的定義,它仍然有點不妥。你可以給我一個例子或者我的程序或者一個開始? – Mdjon26