Hello,
I want to make a function which will cin a string will count the characters and will give the word and the number of the characters back to main(). i wrote the following code but i don't know what type to give to my function.
#include <iostream>
#include <string>
usingnamespace std;
int wordsize (string word,int size){
size=word.size();
return size;
}
int main (int argc, char * const argv[]) {
int size;
string word;
cin >> word;
wordsize(word, size);
return 0;
}
but i get an error :
run
[Switching to process 8970]
Running…
hello
Hangman(8970) malloc: *** error for object 0x100003140: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Program received signal: “SIGABRT”.
sharedlibrary apply-load-rules all
(gdb)
#include <iostream>
#include <string>
usingnamespace std;
int getWord(string& w)
{
cin>>w;
return w.size();
}
int main()
{
int wordSize;
string word;
cout<<"Enter a word, and I will tell you the size.\n";
wordSize=getWord(word);
cout<<"The word was "<<word<<", and the size is "<<wordSize<<".\n";
return 0;
}
To understand how passing by reference works check out this tutorial. It is discussed in the section "Functions(II)"
Thanks but i was looking for a function which would ask for the word and would return in the main program the word and the size of the word.
Also i tried to run your code but i get the same error as mine it runs without any errors but when i give a word something goes bad and it writes
hello
Hangman(9212) malloc: *** error for object 0x100004200: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Program received signal: “SIGABRT”.
sharedlibrary apply-load-rules all
(gdb)
Well i uninstalled all the developers tools and downloaded them from Apple and problem got fixed just like that. By the way the tools i installed from apple were 9 GB :o .
I got a question about the program i want to write.
i want to make a function which will get a char array and will populate it with '-' for all the values.