Csak Zoli
Csak Zoli

Reputation: 428

Entering string array to a function C++

So I am entering an array and a number which is the length of the array to a function called "Write" like this :

string write (int n, char t[100])

To keep it simple i would only like to write the values of the array out whit the help of this function like this:

{
    int i;

    for (i=1;i<=n;i++) {
        if (t[i]=='a') {
        printf("%c" , t[i]);
        }
    }

    return 0;
}

In the int main() only thing I did was I used a scanf for the n variable and gave from 1 to n a 'a' string value in the array.And I called the write function string write(n,t[100]); Here is the whole "main" :

    int main()  
{  
    int i,n;   
    char t[100];  
    scanf("%i" ,&n);  

    for (i=1;i<=n;i++) {
            t[i]='a';
            }
string write (n,t[100]);  
return 0;  
} 

My question is why wont this simple program run I can enter the value of the n but won't print anything out? I must be missing something out whit the declaration's or calling of the function I am new to C++.

Upvotes: 1

Views: 305

Answers (2)

molbdnilo
molbdnilo

Reputation: 66371

The line

string write (n,t[100]);  

in main doesn't call the write function - it defines a variable named "write" of type string, consisting of n elements, each having the same value as t[100] (which is an error in itself, as that is the 101st element of a 100-element array).
To call the function you should write

write(n, t);

You really ought to get a decent introductory book on C++.
There are good lists of them here on SO, and you should make it your first exercise to find them.

Upvotes: 1

tomahh
tomahh

Reputation: 13651

string write(n, t[100]) is the prototype of your function (type omitted). If you want to call write, you need to do something like

int main()  
{  
    int i,n;   
    char t[100];  
    scanf("%i" ,&n);  

    for (i=1;i<=n;i++) {
            t[i]='a';
            }
write(n,t);  
return 0;  
}

Passing t[100] to your write function will give the 100th element of you string to your function, and that is not what you want to do. To pass the whole string, just use t.

Another mistake is that you say write returns a string. But you return 0 in your code, you want to modify the write prototype to int write(int n, char t[100]);

Upvotes: 1

Related Questions