c++ - Whats wrong with the following code -
i have written down code in c++ make words appear in array string input. doesn't works due overflow or something. compiler doesn't show error though.
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; int main() { char a[100]; gets(a); char b[100][100]; int i=0; for(int j=0;j<strlen(a);j++) //runs loop words { int k=0; { b[i][k]=a[j]; k++; } while(a[j]!=' '); i++; } cout<<b[0][0]; return 0; }
if you're going use c strings, need add null terminator @ end of each string
do { b[i][k]=a[j]; k++; } while(j+k<strlen(a) && a[j+k]!=' '); b[i][k] = '\0';
as ppeterka noted, need change loop exit condition avoid infinite loop.
note repeated calls strlen
here , in code wasteful. should consider calculating once before for
loop instead.
Comments
Post a Comment