0

Having trouble with some command line argurments, basically just trying to make a rectangle using command line argrumnents. Here's what I've got

#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]){ int x; int y; int i; int j; x = atoi(argv[1]); y = atoi(argv[2]); fprintf(stderr, "Height & Width Needed\n", argv[0]); return 1; for(i = 0; i < x; i++) for(j = 0; j < y; j++) printf("*"); printf("\n"); return 0; } 

I know this is amateur hour but I'm just starting out. Added stderr for argv[0] statement, included atio, every time compile I just get my usage statement. I tried adding curly braces on my outer loop only, and then on the outer and inner loop, still just getting my stderr every time I run with commands.

9
  • 6
    int x = argv[1]; --> x = atoi(argv[1]); (#include <stdlib.h>) Commented Jul 2, 2017 at 2:40
  • Command line arguments are strings. They must be converted to ints, if an int is what's desired. atoi is one way. Other options: strtol and sscanf. Commented Jul 2, 2017 at 2:43
  • 1
    for(i = 0; i <= x; i++) maybe --> for(i = 0; i < x; i++){ ... } Commented Jul 2, 2017 at 2:43
  • Thanks @BLUEPIXY, I can't believe I forgot atoi.. so I want to be able to do this without using scanf, when I put that in I'm getting "redeclaration of 'x' with no linkage.. Commented Jul 2, 2017 at 3:06
  • 1
    You don't have enough braces. Commented Jul 2, 2017 at 4:05

1 Answer 1

1

C is not like Python, you must put bracket to create block. There is no if structure around your return 1; so it will be always executed.

#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s height width\n", argc > 0 ? argv[0] : ""); return 1; } int x = atoi(argv[1]); int y = atoi(argv[2]); for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { printf("*"); } printf("\n"); } } 

Note: atoi() don't detect error, use strtol() instead.

Sign up to request clarification or add additional context in comments.

2 Comments

@Stargatuer, thanks for the help, I added this but It still doesn't seem to work. It just does nothing. Added the argc != 3 portion as well with an stderr but it still returns nothing when I (example) ./rec 3 9.....nothing, ugh I know it's something small I'm missing
sorry about that. Still confused a bit on how to properly comment. I do appreciate the help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.