Write to C files

Asked

Viewed 322 times

-1

Eai personal. I need to do a work in C that I have to create files with numerical sequences and create another file with the intersection of those numbers and such... However, I can’t write these (int) in the file, like, it has to be 10 values, but at the time of running I end up entering with much more values than expected.

    printf("Entre com os valores do arquivo: \n");
    for(cont=1; cont <= *argv[3]; cont++) {
        scanf("%c", &ch);
        fputc(ch, f1);
    }

*argv[3] is the size user entered for the amount of values.

  • Friend I believe that the error of your code is not in this specific block. I did not find any error in this part of the code.

  • 1

    Why the asterisk before argv[3]? You don’t want the value of this position, so why take the address?

1 answer

0

The problem is how you are using the parameter argv in his for:

for(cont=1; cont <= *argv[3]; cont++) {
-----------------------^ aqui

argv is actually an array of strings that is normally declared as:

int main(int argc, char *argv[]) {

Soon *argv[3] will actually give the first character of the third parameter that will be converted to integer based on its ASCII value. So if you call the program with:

programa.exe param1 param2 20

The 20 will stay in the arg[3] as an array of characters, and argv[3][0] or *argv[3] will give '2', that converted to whole will give 50.

If you want to use the third integer parameter you can do the conversion using atoi:

for(cont=1; cont <= atoi(argv[3]); cont++) {

In addition to reading with %c is not the Enter press, which will be for the next reading, resulting in fewer readings than intended. A simple solution is to start reading with a space before the %c:

scanf(" %c", &ch);

Documentation for atoi function

Browser other questions tagged

You are not signed in. Login or sign up in order to post.