Get size of input in console - c++

How would you get the size input string to console or size of valid characters in buffer?
char buffer[100];
cin >> buffer;
I'm looking to put the '\0' where the input ends.

Prefer using std::string, instead of char* or char[]. That makes such things easy! The problem with char buffer[100] is that if the size of input string is more than 100, then your cin >> buffer would invoke undefined behavior, as it would attempt to write beyond the array. This problem can easily be avoided if you use std::string.
std::string input;
cin >> input; //this can read string of any unknown size!
cout << "length of input string : " << input.size()<< endl;
You can also use input.length() instead of input.size(). They return the same value.
Online Demo : http://www.ideone.com/Wdo31

The question is moot. When the user types more than 100 characters, you have a buffer overrun. You may crash. If not, you got a security issue at best. You shouldn't do this. Read the input a character at a time, or use a safer string library. gets_s comes to mind if it's supported on your platform.
But in answer to your question, this might be what you need:
char buffer[100] = {}; // zero-init the entire array
int length = 0;
cin >> buffer;
length = strlen(buffer); // length is the length of the string

You don't need to (and quite possibly, can't). Instead, use a std::string instead of a char buffer.

Related

Know size of argument in fscanf(fp , "%s" , strr1)

char str1[10];
fscanf(fp , "%s", str1);
I want to know size of %s before assigning to str1 to avoid crashing in case of huge input data.
Since this is C++, you don't have to rely on fscanf. We can avoid buffer overflow altogether by using std::istream:
std::string readWord(std::istream& input) {
std::string word;
if(input >> word) {
return word;
} else {
// Handle error
}
}
This will automatically read characters until reaching the first whitespace character is encountered, and it'll automatically allocate memory as needed.
You can specify the maximum number of characters to read:
fscanf(fp, "%9s", str1);
This will not write more than 10 chars into str1 including the null terminator.
But in C++ you should use streams and strings which are safe in this respect.

how can I limit a user to input 8 characters into string(dynamic char array)in c++?

int size;
cout<<"enter string size"<<endl;
cin>>size;
char * string1 = new char[size];
well hello,im working on a project and one of my functions purpose is to get a dynamic char array as arg which sends to the output the first letters of the words in the string.
so the user decides the string length (for the initialized dynamic array),
but then how can i ensure he won't exceed the length of the array he chose?(the compiler does not Refer to it as a mistake).
can i force the 'cin' operator to limit itself?
Using std::string is better, but...
char input [8];
cin.getline (input, 8);
Note, there may still be data in the input buffer after this that you may need to deal with.
Edit
Given the original code in the question:
cin.getline(string1, size);
Just have them input into a std::string. Don't bother with the manual memory management.
std::cout << "Enter your name.\n> ";
std::string name;
std::cin >> name;
Then, if you need to only pass the first 8 characters or something, use name.substr(...).
You really ought to be std::string, but if you really want to use a character array, you should use:
cin.getline(string1, 8);
This gets 8 characters from the user input.
cin getline works as followed:
It extracts characters, without any formatting and storms them as an c-string. It will stop extracting characters when either the new line character is reached, a set char deliminator, or until the number of characters specified has been extracted.
You can make this approach with std::string. For example:
const int maxchar = 8;
string str;
cin >> str;
if (str.size() > maxchar )
{
err << "The input is too long." << endl;
return 1;
}

How to read a string in the form of char array using cin?

how to read a string in the form of char array using cin and using other string functions in cpp.
I tried using a while loop but what is the condition for ending the loop if the size is not given.
Like i used while('\0') but it didn't worked.
You could use cin.getline():
char s[1024];
std::cin.getline(s, 1024, '\n');
std::cout << s << std::endl;
If you have a character array, e.g:
char szExample[] = "Hello World";
You can process it with:
char* ptr = &szExample[0];
//Look while ptr doesn't point to null terminator
while( *ptr ) {
//Do something...
//Increment pointer
ptr++;
}
if size is not given then you can set char array size to maximun as u wanted and use
scanf() for reading the char array and also add header stdio.h for use scanf() .
example:
#include<stdio.h>/#include<cstdio>
char array[100000];
scanf("%s",&array);
for knowing the length of inputed char use strlen()
int size=strlen(array);
printf("%s\n",array);
printf("%d\n",size);
input:
ghostrecon
output:
ghostrecon
10
If you are not strict about using a char array it's better to use string datatype.
string s;
char delimiter = '\n';
getline(cin, s, delimiter);
Here s will read whole line.
If you can keep delimiter as '\0' and then s will contain the whole file till EOF.

Reading a string of unknown length from a file

I need to read a text file that's in this format:
n k
S1
S2
S3
.
.
.
Sn
N being and integer, and S's being strings. Now, as far as I've seen a string cannot be read with fscanf function, but rather an array of char's has to be used.
The problem is that I need to set the length of the character array even though I have no way of knowing how long a word will be:
in = fopen("01.in", "r");
int N, k;
fscanf(in, "%d %d", &N, &k);
for (int i=0; i<N; i++){
char temp[100];
fscanf(in, "%s", temp);
}
So is there a way to maybe use vectors or something?
Or maybe in the off case that this problem cannot be solved, can I convert a string of chars into a string, and then create a vector of strings?
Why not use std::ifstream and std::getline something like this:
std::ifstream in("01.in");
int N, k;
if(!(in >> N >> k))
{
std::cerr << "Error reading file!" << '\n';
return EXIT_FAILURE;
}
std::string line; // read lines into this
int i = 0;
while(i < N && std::getline(in, line))
{
// deal with line here
++i; // keep track
}
The first step towards code sanity here is to stop using char arrays and start using std::string instead. The big difference between the two is that an array's size is set in stone at compile time, whereas a std::string's initial size can be can be chosen at runtime, and it can also grow and shrink while the program runs.
Now, as far as I've seen a string cannot be read with fscanf function,
but rather an array of char's has to be used.
Since C++11, that's not strictly true. std::strings are in many ways compatible with C functions. For example, you can safely get a pointer to the underlying buffer with &s[0]. Therefore, you could technically do this:
std::string temp(100, '\0');
fscanf(in, "%s", &temp[0]);
But that has not gotten us far. Apart from some other bad things about this "solution" (unidiomatic, undefined behaviour if too many characters are read, wasteful if too few characters are read), as you can see, the original problem still persists; the number 100 is hard-coded in the program. This is the real problem, as you have also said in the comment you added:
What I mean is what if I get a string that's longer than 100 characters?
The answer to that is: Just don't use fscanf anymore. Use std::ifstream along with the std::getline function. std::getline reads a whole line, i.e. everything until the next line break, and stores the result in a std::string. Size and memory management are all handled automatically for you:
std::ifstream is("01.in");
std::string temp;
std::getline(is, temp);

c++, get phone number from txt file

I'm trying input a phone number in the format: 555-555-5555 into a struct with three int's. I've tried using getline with a delimiter of "-", but I keep getting the error: "cannot convert parameter 1 from 'int' to 'char *'".
I tried creating a temp char* variable to store the number in and then type casting it to int, but that didn't work.
How should I go about doing this?
Thanks
edit:
here's some of the code:
void User::Input(istream& infile) {
char* phone_temp;
...
infile.getline(phone_temp, sizeof(phoneNum.areaCode), "-");
phoneNum.areaCode = (int)phone_temp;
...
}
Since you are posting this as a c++ question, and not a c question, Use istringstream
http://www.cplusplus.com/reference/iostream/istringstream/
From my head it your code would become something like:
std::string sPhoneNum("555-555-5555");
struct
{
int p1;
int p2;
int p3;
} phone;
char dummy;
std::istringstream iss(sPhoneNum);
iss >> phone.p1; // first part
iss >> dummy; // '-' character
iss >> phone.p2; // second part
iss >> dummy; // '-' character
iss >> phone.p2; // last part
EDIT:
now that you have posted example code, I see you already start with an istream, you can just use the >> operator directly, no need to create another istringstream operator. See examples: http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/
Also, stay away from c-style conversion methods with char * and atoi stuff if you don't have to, working with std::string and istreams is the "right" C++ way. It avoids memory leaks and other nasty problems.
Reading a phone number from a stream:
Assuming the number is well formatted:
void User::Input(istream& infile)
{
int part1;
int part2;
int part3;
char dash1;
char dash2;
infile >> part1 >> dash1 >> part2 >> dash2 >> part3;
/*
* !infile will return false if the file is in a bad state.
* This will happen if it fails to read a number from
* the input stream or the stream ran out of data.
*
* Both these conditions constitute an error as not all the values will
* be set correctly. Also check that the dash[12] hold the dash character.
* Otherwise there may be some other formatting problem.
*/
if ((!infile) || (dash1 != '-') || (dash2 != '-'))
{
throw int(5); // convert this to your own exception object.
}
}
if I understand correctly, try atoi() or stringstream to convert from char* to int
See this example on how you can tokenize the line. This question will also help.
Then use atoi to convert string to int.
You can't cast a char* to an int and expect a correct value. A char* is an address in memory, so when you cast it to int, you'll get a memory address in your int. You need to call a function, such as atoi() to algorithmically convert the data char* is pointing to into an integer.
Another viable option, although not quite C++, is:
char a[10],b[10],c[10];
scanf("%d-%d-%d", a, b, c);
It appears you're trying to convert a char to an integer, in which case you'd want to use the atoi function or a string stream.
rather than using infile.getline() use the free standing version with a std::string:
getfile(infile, buffer);
After that, if you'd like you can do an addition getline():
istringstream phonenumber(buiffer);
string areacode = getline(phonenumber, part1. '-');
or you can use the extractor >> (that's what it's for!)
int areacode;
phonenumber >> areacode;
Just a side note: if you're using char* do make sure you allocate space for it, or at least point to allocated space.