c++ - What is the length of my array? -
hello i'm having trouble strlen , arrays, keeps saying string length one? if great here's code:
#include <iostream> using namespace std; #include <cstring> int main() { char word1[20]; int len = strlen(word1); cout << "enter word!\n"; cin.get(word1, 20, '\n'); cin.ignore(50,'\n'); cout << len; }
just read , forth in comments, updating answer try , give more intuition behind what's going on.
char word1[20]; sets place in computer's memory can filled data 20 characters. note statement alone not "clear" memory of whatever there. sfjac has pointed out, means literally in space. it's highly unlikely whatever in space character or code readily understand.
int len = strlen(word1); creates integer , sets equal value of number of characters in word1. note that, because have not specified content word1, you're taking length of whatever happened in memory space already. you've limited maximum 20, in case, whatever data junk in there giving length of 1.
cout << "enter word!\n"; prompt user word
cin.get(word1, 20, '\n'); cin.ignore(50,'\n'); word, store in word1. @ point, word1 defined actual content. - you've defined variable len. computer not know automatically redefine you. follows steps provide, in order.
cout << len; print value stored in len. because len created prior user entering data, len has absolutely nothing user entered.
hope helps give intuition beyond 1 question!
Comments
Post a Comment