How to read comma separated integer inputs in java
you can use the nextLine method to read a String and use the method split to separate by comma like this:
public static void main(String args[])
{
Scanner dis=new Scanner(System.in);
int a,b,c;
String line;
String[] lineVector;
line = dis.nextLine(); //read 1,2,3
//separate all values by comma
lineVector = line.split(",");
//parsing the values to Integer
a=Integer.parseInt(lineVector[0]);
b=Integer.parseInt(lineVector[1]);
c=Integer.parseInt(lineVector[2]);
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}
This method will be work with 3 values separated by comma only.
If you need change the quantity of values may you use an loop to get the values from the vector.
How do you allow comma to be used for user input for integer based input c++?
Read the input in as a string:
std::string input;
std::cin >> input;
Remove the commas, using the erase-remove idiom:
input.erase(std::remove(input.begin(), input.end(), ','), input.end());
which from C++20 you can write like this:
std::erase(input, ','); // C++20
Convert the string to an int:
int player_input = std::stoi(input);
read comma-separated input with `scanf()`
The comma is not considered a whitespace character so the format specifier "%s"
will consume the ,
and everything else on the line writing beyond the bounds of the array sem
causing undefined behaviour. To correct this you need to use a scanset:
while (scanf("%4[^,],%4[^,],%79[^,],%d", sem, type, title, &value) == 4)
where:
%4[^,]
means read at most four characters or until a comma is encountered.
Specifying the width prevents buffer overrun.
Related Topics
Print Heart Shape With Words Inside
Combining Multiple for Loops into Single Iterator
What Are Rvalues, Lvalues, Xvalues, Glvalues, and Prvalues
Accessing Inactive Union Member and Undefined Behavior
Why Does C++ Code For Testing the Collatz Conjecture Run Faster Than Hand-Written Assembly
What Are the Evaluation Order Guarantees Introduced by C++17
Choice Between Vector::Resize() and Vector::Reserve()
How to Expand a Tuple into Variadic Template Function'S Arguments
Count How Many Times Elements in an Array Are Repeated
What Are the Basic Rules and Idioms For Operator Overloading
Passing a 2D Array to a C++ Function
When Does Invoking a Member Function on a Null Instance Result in Undefined Behavior
How to Parse a String to an Int in C++