Prerequisition
- I am using Arch based Linux
- gcc and clang installed via
pacman
Input Output
🚴 PRACTICE | simple cli app
copy this code to file main.cpp
#include <iostream>
int main() {
// Getting stdin (standard input):
std::cout << "Enter a line of text: " << std::endl;
return 0;
}
run with gcc
g++ -Wall -std=c++20 main.cpp -o test
or run with clang
clang++ -Wall -std=c++20 main.cpp -o test
run the output file ./test
🚴 PRACTICE | using namespace
try this code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string input;
getline(cin, input);
stringstream ss(input);
int number;
int sum = 0;
while (ss >> number) {
sum += number;
}
cout << sum << endl;
return 0;
}
Explanation
iostream
: For input and output (std::cin, std::cout).sstream
: For string streams (std::stringstream).string
: For string manipulation (std::string).std::string input;
declares a string variable to store the input.std::cout << "Enter numbers separated by spaces: ";
prompts the user for input.std::getline(std::cin, input);
reads the entire line of input, including spaces.std::stringstream ss(input);
creates a string stream from the input string. This allows us to extract numbers from the string.int number;
declares an integer variable to store each number.int sum = 0;
initializes the sum to 0.while (ss >> number)
: This loop reads numbers from the string stream until there are no more numbers.ss >> number
extracts the next number from the string stream and stores it in the number variable.
references:
- cppreference.com