so I'm currently trying to read user input into a char array, but every single example I've looked at defines the size of the array upon its initialization. What I'm looking for, essentially, is a way to read user input (perhaps with getline, as I would want to read user input as a string) and store it in an array.
Let's say a user inputs this into the program:
This is a string
I would want the array size to be able to fit that string, and place the null terminator after the "g". Then, another user could put a string of any size that they so desired into the program, but I would basically want my program to always make the array size just enough to contain what was read in from input.
I haven't been able to get this working and it's been a couple of hours of browsing endless pages, so any help would be appreciated! Thanks.
As Tony Delroy said on his comment (I can't comment yet), you should be using std::string .
If you really need an char array, as parameter to a function for example, you can use the function c_str() to get the content of the std::string as a const char* array or if you need a char* array, you can copy the content of the array given by c_str() to a dynamically allocated array, using
char* cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
As an addend, you need to include the header cstring in order to use the function strcpy and need to use delete[] cstr to delete the char* when you're not going to use it anymore
#include <iostream>
#include <cstring>
using namespace std;
// string argument as std::string
void foo(string str) {
// function body
}
// argument as const char*
void bar(const char* str) {
// function body
}
// argument as char*
void baz(char* str) {
// function body
}
int main() {
string str;
getline(cin, str);
foo(str);
bar(str.c_str());
char* cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
baz(cstr);
delete[] cstr;
return 0;
}
you should use std::string for that. the null terminator has no use in std::string, because you can just use:
string.size()
to get the size of the user input.
if want to traverse a string like a char array one by one it should look like something like this:
std::string input;
std::getline(std::cin, input);
for (int i = 0; i < input.size() ; i++)
{
std::cout << input[i];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.