how to make input on command line?

I am wondering how to make input on command line?
Last edited on
Start with a simple test program that prints out all the arguments you feed into it.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
    using namespace std;
    for (int i = 0; i < argc; i++)
    {
        cout << "argv[" << i << "] = " << argv[i] << '\n';
    }
}


To convert char array to number, you can do something like:

1
2
3
4
5
6
if (argc < 4)
{
    cout << "Not enough arguments?\n";
    return 1;
}
int n = std::stoi(argv[3]);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char** argv) {
    if (argc != 4) {
        cerr << "Usage: creditrating TRAIN TEST MINLEAF\n";
        return 1;
    }
    
    string train = argv[1];
    string text = argv[2];
    int minleaf = stoi(argv[3]);
    
    cout << train << '\n' << text << '\n' << minleaf << '\n';
}

This is my make file:
1
2
3
4
5
creditrating: creditrating.o
	g++ creditrating.o -o creditrating.bin

creditrating.o: creditrating.cpp
	g++ -c creditrating.cpp
You need to compile it with C++11, probably sth. like -std=c++11
I also would add -Wall -Wextra -Wshadow -Wpedantic -Werror
Did you edit your OP...? Don't do that, it just makes it more confusing for other people reading your post, and makes the people who reply to you look like lunatics.

You're compiling in C++98 (i.e. the original standard). Functions like stoi and stod, and "for each" loops were not in the language until C++11 (finalized basically a decade ago at this point).

Are you using the Windows version of g++? Try to enable -std=c++11 to your command-line arguments.
Also, turning on warnings like at least -Wall is suggested.
Last edited on
I change my makefile. It now runs ok. Thank you for you help!
Topic archived. No new replies allowed.