-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_input_cpp.cpp
More file actions
61 lines (41 loc) · 1.36 KB
/
Copy pathget_input_cpp.cpp
File metadata and controls
61 lines (41 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// C++ implementation of asking for user input using std::string
#include "get_input_cpp.h"
#include <iostream>
#include <string>
#include <cstring>
#include <climits>
// C-compatible function (stack-based, similar to get_input.c)
extern "C" void ask_name_cpp(char *name, size_t size) {
std::cout << "Enter your name (C++ version): ";
// check size limmit
if (size > INT_MAX) {
size = INT_MAX;
}
std::string input;
if (std::getline(std::cin, input)) {
// copy to buffer, ensuring null termination
size_t copy_len = std::min(input.length(), size - 1);
std::strncpy(name, input.c_str(), copy_len);
name[copy_len] = '\0';
std::cout << "Hello from C++, " << name << "!" << std::endl;
} else {
name[0] = '\0'; // Empty string on error
std::cerr << "Error: Failed to read input." << std::endl;
}
}
// Pure C++ version using std::string (not callable from C)
//namespace InputCpp {
// std::string ask_name_string() {
// std::cout << "Enter your name (C++ std::string version): ";
//
// std::string name;
// if (std::getline(std::cin, name)) {
// std::cout << "Hello from C++, " << name << "!" << std::endl;
// return name;
// }
//
// std::cerr << "Error reading input" << std::endl;
// return "";
// }
//}
//