2011-12-14 132 views
2

我有一组字符串,它看起来像
“4 7 14 0 2 blablabla”
“3 8 1 40 blablablablabla”
取可变数目的整数...
C++解析,从字符串

第一个数字N对应于后面会有多少个数字。
基本上,一个字符串的格式是N + 1个数字,用一个空格分隔,然后在不需要的末尾添加未知数量的不相关字符。

因为我事先不知道数字N,所以如何获得变量或动态结构中的所有数字?

换句话说,我想是这样的:

sscanf(s, "%d %d %d %d",&n,&x,&y,&z); 

这将字符串中的工作,不管有多少个号码。

回答

4
int input; 
std::vector<int> ints; 
while(std::cin >> input) //read as long as there is integer 
     ints.push_back(input); 
std::cin.clear(); //clear the error flag 
//read the remaining input which most certainly is non-integer 
+0

嗡嗡声,我不确定这是否回答OP问题:如果输入字符串是'2 7 9 14 23 foo bar`?只应读取“7”和“9”,忽略“14”,“23”,“foo”和“bar”。 – 2011-12-14 10:27:12

0

初始化你的字符串的istringstream,并从中读取:

std::istringstream ss(s); 

int N; 
ss >> N; 

std::vector<int> a(N); //int* a = new int[N]; 
for (int i=0;i<N;i++) 
    ss >> a[i]; 
+0

为什么不'的std :: VECTOR`? – jrok 2011-12-14 10:06:28

+0

好点。它是`vector`。 – Vlad 2011-12-14 10:13:01

2
std::string s = "3 54 -4 42 fdsvadsdsberwte"; 
std::istringstream source(s); 

std::vector<int> ints; 

int num = 0; 
int temp = 0; 

if (source >> num) // read the first number and if it succeeds, read the rest 
{ 
    while(source >> temp) ints.push_back(temp); 
    // Here, I'd compare the size of the vector with what was 
    // expected (num) and act accordingly. 
} 
else 
{ 
    // format error 
} 
6

的第一件事是将输入分解成线,用 getline读它。这将极大地方便错误恢复和在出现错误时重新同步。它也将促进解析; 这是几乎每次在 的换行符输入都很重要时应采用的策略。之后,您使用std::istringstream至 解析该行。喜欢的东西:

std::vector<std::vector<int> > data; 
std::string line; 
while (std::getline(input, line)) { 
    std::istringstream l(line); 
    int iCount; 
    l >> iCount; 
    if (!l || iCount < 0) { 
     // format error: line doesn't start with an int. 
    } else { 
     std::vector<int> lineData; 
     int value; 
     while (lineData.size() != iCount && l >> value) { 
      lineData.push_back(value) ; 
     } 
     if (lineData.size() == iCount) { 
      data.push_back(lineData); 
     } else { 
      // format error: line didn't contain the correct 
      // number of ints 
     } 
    } 
} 
0

你可以做这样的事情:

std::string buffer; 
while(std::getline(in, buffer)) { // read a line 
    std::istringstream str(buffer); // put line in a stringstream for parsing 
    int count; 
    str >> count;     // read first number 
    std::vector<int> numbers(count); // reserve space for other numbers 
    for(int i = 0; i < count; i++) { // read other numbers 
     str >> numbers[i]; 
    } 
}  
0

您可以使用动态数组类型的动态数组和链表。读取一行后,使用数字N初始化数组,并在每个索引上顺序插入数字。将包含行数据的节点插入链表。

伪代码:

int *lineNumbers; 
lineNumbers = new int[N]; 

List<int*> data; 
data.insert(lineNumbers);