-1

The task was to find all the words in array s with numbers inside them. The word are spaced with " " and at the end of the array there is always a ..

My code doesn't exit the while loop and I don't know why:

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cctype>

using namespace std;
void Numbers(char s[], vector<pair<int, char>>& nums){
    char *token;
    int zero = 0;
    token = strtok(s, " ");
    for(int i = 0; i < strlen(token); i++){
        if(isdigit(token[i])){
            nums.emplace_back(zero, *token);
        }
    }
    while(token != NULL){
        zero ++;
        token = strtok(NULL, " ");
        for(int i = 0; i < strlen(token); i++){
            if(isdigit(token[i])){
                nums.emplace_back(zero, *token);
            }
        }
    }
}
int main() {
    vector<pair<int, char>> nums;
    char s[256];
    gets(s);
    Numbers(s, nums);
    cout << nums.size();
    for (int i = 0; i < nums.size(); i ++){
        cout << nums[i].first << " " << nums[i].second << endl;
    }
    return 0;
}

I tried to run the code with qw6wqe esd9f 0gfgkj. input with debug, token changes, all should be working, but it never gets out of the loop.

Tried using break but that didn't work.

1 Answers1

2

Your program has undefined behaviour. When you reach the end of the input, token is a null pointer, and you then pass it to strlen.

You need to stop processing when strtok returns a null pointer.

void Numbers(char s[], vector<pair<int, char>>& nums){
    int count = 0;
    for(char * token = strtok(s, " "); token = strtok(nullptr, " ");){
        for(int i = 0; i < strlen(token); i++){
            if(isdigit(token[i])){
                nums.emplace_back(count, *token);
            }
        }
        count++;
    }
}
Caleth
  • 52,200
  • 2
  • 44
  • 75