Get unlimited char in Cpp [duplicate] - c++

This question already has answers here:
Dynamically allocate user inputted string
(4 answers)
Closed 5 years ago.
I want to get unlimited chars, actually I created char*, I use cin for it, and I want to change it to string.
I don't know the length of the input which user enters, so I made this solution for myself.
Can someone tell me plz, how to get a char* without knowing the size of input and converting to string.
thanks.

Since it is C++. Just use std::string
If you really need to use char* look at this topic

Instead of using a char *, use the standard library.
#include <string>
#include <iostream>
int main()
{
std::string data;
std::getline(std::cin, data);
std::cout << data << '\n';
}
This will read a string of any length (at least, until a newline is entered, which will not be included in data) and then print it out.
You might wish to also check the state of std::cin to test if any errors occurred.

Related

How can I store an array of char in an array in c++

Hi so I'm writing code in C++ that asks the user to submit a message like "the house is green" and then store it an array that stores messages so this is what i have so far
#include <iostream>
using namespace std;
char message[100];//limits the message to 99 characters.
char arrayOfMessages [5];
cout<<"Please enter the message";
cin>>message;
I canĀ“t figure out a way to make
arrayOfMessages[0]= message; // since doing this only stores the first position
Appreciate the help or suggestions if I should do something different in obtaining the message.
Also this is an over simplified version but is the gist of what im trying, however im trying to make the array message be temporary so i can reuse it to request up to 5 messages from the user , in my code version I did this with a while cycle.
Use std::vector and std::string:
#include <iostream>
#include <vector>
#include <string>
int main() {
//char message[100];//limits the message to 99 characters.
std::string message; //use std::string instead of char[]
std::vector<std::string> arrayOfMessages;
arrayOfMessages.reserve(5); //reserve space for 5 strings
std::cout << "Please enter the message";
// std::cin >> message;
std::getline(std::cin, message); //use this if there's more than one word
arrayOfMessages.emplace_back(message); // put the message in the array
}
std::vector is a dynamic array which can contain elements of any one type. Here we store std::string type in it. It will automatically grow. For example if you have 6 strings, it's size will automatically increase to 6 when you emplace_back another element.
std::string is how we do strings in C++. char [] is also possible, but don't use it unless you really have a very good reason to.
emplace_back will append the string to the end of the array.
So I found the simplest answer was to simply change the
char arrayOfMessages [5];
to
string arrayOfMessages [5];
and then just do a simple
arrayOfMessages [0]=message;
And that worked, so thanks for everyone's help and suggestions!!

Converting char* to int and converting back to the same char array [duplicate]

This question already has answers here:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Why can't I write to a string literal while I *can* write to a string object?
(4 answers)
Is it possible to modify a string of char in C?
(9 answers)
Closed 8 years ago.
Basically, I am trying to increment the int value of port. This should be easy but I am a little stuck.
It compile fine, but I got this error when I run it:
Access violation writing location 0x001f5834
#include "stdafx.h"
#include "iostream"
using namespace std;
#define TESTING "5002"
int main()
{
char* port = TESTING;
int portint;
sscanf ( port, "%d", &portint );
portint++;
cout << portint << endl; // it works fine up to here, it prints 5003
sprintf ( port, "%d", portint);
return 0;
}
By default, compiler treats string literals as immutable, and an attempt to modify the contents of one results in an access violation error at run time because these strings are put into code segment, and it's read only. In your case, TESTING is a string literal, you can't not change its values. Try:
char port[] = "5002";
Meanwhile, the compiler should have warning on this: when you assign a const char* type to a char* type.
MS C++ compiler has a compiler option regards this: Zc:strictStrings.
You are trying to write "5003" back into "5002". "5002" is a string literal and cannot be written to.
I'll try to find a good duplicate for this question, because it has been asked in many ways, many times.
In your usage, "5002" becomes a static array of characters and as such can not be modified. I believe K&R address this, but I don't have the book in front of me right now. Behavior would be different if you had declared an array.

How to use printf for strings? [duplicate]

This question already has answers here:
printf with std::string?
(9 answers)
Closed 9 years ago.
So this is my code
string name;
cout <<"\n Enter Your name : \n";
cin >> name;
printf("%s" , name);
and for some weird reasons codeblocks crashes at this
why ?
also how could I fix it ?
thanks
You should compile with all warnings (e.g. g++ -Wall). You'll get a useful warning. You want to use c_str like this
printf("%s", name.c_str());
BTW, why use printfand why do you forget a \n at the end of the printf format string? (or use fflush)
Better code:
cout << name << endl;
If you need to pass your std::string to a function that accepts / uses C-style strings (const char *) for input, use .c_str(). It returns a const char *.
This is what you should do when needing to work with existing libraries, system calls, etc. For your own code, it is usually better to find a more C++ way of doing it.
In this case:
std::cout << name << std::endl;

C++ Strings single chars [duplicate]

This question already has answers here:
How to convert string to char array in C++?
(11 answers)
Closed 8 years ago.
I've just started learning C++ and im kinda confused about strings.
I first need a input word and save every single char in the certain position of a char-Array.
But strings are basically char-Arrays, aren't they?
But this does not work:
char word[];
cin >> word[];
Whereas this works but I dont know how to fill the chars into an Array.
string s;
cin >> s;
I've tried this so far, but i got an compile error:
string s;
cin >> s;
char word[] = s;
I'm sorry, I've just started programming and I wonder if anyone has some advice for me :)
char word[];
You need to give the size of the array. Then, you can take input to it directly. If you wish to copy read the std::string to the character array, then you need to use safe string copy functions like strncpy. For example -
char word[10];
std::string str("Hello");
strncpy(word, str.c_str(), sizeof(word));
However, std::string is recommended in C++ rather than working with character arrays.

Length of a char array

I have the code like this:
#include <iostream.h>
#include <fstream.h>
void main()
{
char dir[25], output[10],temp[10];
cout<<"Enter file: ";
cin.getline(dir,25); //like C:\input.txt
ifstream input(dir,ios::in);
input.getline(output,'\eof');
int num = sizeof(output);
ofstream out("D:\\size.txt",ios::out);
out<<num;
}
I want to print the length of the output. But it always returns the number 10 (the given length) even if the input file has only 2 letters ( Like just "ab"). I've also used strlen(output) but nothing changed. How do I only get the used length of array?
I'm using VS C++ 6.0
sizeof operator on array gives you size allocated for the array, which is 10.
You need to use strlen() to know length occupied inside the array, but you need to make sure the array is null terminated.
With C++ better alternative is to simple use: std::string instead of the character array. Then you can simply use std::string::size() to get the size.
sizeof always prints the defined size of an object based on its type, not anything like the length of a string.
At least by current standards, your code has some pretty serious problems. It looks like it was written for a 1993 compiler running on MS-DOS, or something on that order. With a current compiler, the C++ headers shouldn't have .h on the end, among other things.
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string dir, output, temp;
std::cout<<"Enter file: ";
std::getline(cin, dir); //like C:\input.txt
std::ifstream input(dir.c_str());
std::getline(input, output);
std::ofstream out("D:\\size.txt");
out<<output.size();
}
The getline that you are using is an unformatted input function so you can retrieve the number of characters extracted with input.gcount().
Note that \e is not a standard escape sequence and the character constant \eof almost certainly doesn't do what you think it does. If you don't want to recognise any delimiter you should use read, not getline, passing the size of your buffer so that you don't overflow it.