C++ Strings single chars [duplicate] - c++

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.

Related

Get unlimited char in Cpp [duplicate]

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.

Dynamically allocated strings in C

I was doing a relatively simple string problem in UVa's online judge to practice with strings since I've been having a hard time with them in C. The problem basically asks to check if a string B contains another string A if you remove the 'clutter' and concatenate the remaining characters, for example if "ABC" is contained in "AjdhfmajBsjhfhC" which in this case is true.
So, my question is how can I efficiently allocate memory for a string which I don't know its length? What I did was to make a string really big char Mstring[100000], read from input and then use strlen(Mstring) to copy the string the a properly sized char array. Something like :
char Mstring[100000];
scanf("%s",Mstring);
int length = strlen(Mstring);
char input[length+1]={0};
for(int i = 0; i<length;i++){
input[i]=Mstring[i];
}
Is there a better/standard way to do this in C? I know that C does not has a great support for strings, if there is not a better way to do it in C maybe in C++?
If you have the option of using C++ (as you mentioned), that is going to make your life a lot easier. You can then use a STL string (std::string) which manages dynamically sized strings for you. You can also drop the old scanf() beast and use std::cin.
Example:
#include <iostream>
#include <string>
void main()
{
std::string sInput;
std::getline(std::cin, sInput);
// alternatively, you could execute this line instead:
// std::cin >> sInput;
// but that will tokenize input based on whitespace, so you
// will only get one word at a time rather than an entire line
}
Describing how to manage strings that can grow dynamically in C will take considerably more explanation and care, and it sounds like you really don't need that. If so, however, here is a starting point: http://www.strchr.com/dynamic_arrays.

Input hex strings as char at once

I have a strings like this:
315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5
Is there a way to read it from file at once into string object keeping in mind that every 2 chars are hexadecimal representation of byte? I.e. I need a reading with conversion from hex to char.
UPDATE
Guys, please read carefully what I asked.
I'm able to write conversion functions and looping along a string.
BUT I need read a string of hex to a string of char at once.
No any looping. No conversions by hands.
Something like cin >> ...some string variable...
Thanks.
UPDATE2
Imagine I have the string "315c4eeaa8b5". I want to write something like cin >> string_var and get that string_var containing exactly the "'0x31','0x5c','0x4e','0xea','0xa8','0xb5'". Please note, this last is an ordinal std::string. I.e. 0x31,0x5c,etc are codes of chars.
Hope it makes thing clearer.
Either you code something up or you use something that already exits. If you are using C++ IO streams then I would suggest taking a look at Boost.IOStreams library and especially its Filtering Streams concept. You can use the tab expanding 2.2.5.2 input_filter tutorial example as a base for your hexadecimal input filter implementation.
You can use istream::opeartor>> with the std::hex manipulator to parse as hexadecimal:
ifstream in("...");
char buffer[3];
vector<char> chars;
while (in.read(buffer, 2))
{
buffer[2] = '\0';
char c;
istringstream(buffer) >> hex >> c;
chars.push_back(c);
}

How to use strtok() using a string argumnet instead of character array? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Using strtok with a string argument (instead of char*)?
When using strtok() i do the following
char str[300];
while(infile) {
infile.getline(str,300);
char* token=strtok(str," ");
How can i use a string instead of the character array char str[300];
is there a way to use it to be like this,string str;
while(infile) {
infile.getline(str,300);
char* token=strtok(str," ");
I don't think you can, at least not without great care; strtok() modifies its argument, writing a \0 into it after every recognized token, and generally behaves like a function that's poorly behaved even for C, much less C++. My advice would be to look for a native C++ solution instead.
If you mean an std::string, you cannot, strtok only works with char*.
An easy solution could be that of strdup your string.c_str, and pass it to strtok.
string str;
while(infile)
{
getline(infile, str);
char* token=strtok(&str[0], " ");
}
Clean it ain't, but it will work.
EDIT: My mistake, this may not work in all circumstances.

Getting input from user using cin [duplicate]

This question already has answers here:
C++ "cin" only reads the first word [duplicate]
(5 answers)
Closed 4 years ago.
I am using Turbo C++ 3.0 Compiler
While using the following code ..
char *Name;
cin >> Name;
cout << Name;
When I gave input with space ... its only saving characters typed before space ..
like if I gave input "QWERT YUIOP" ... Name will contain "QWERT";
Any explaination why ??
When cin is used to read in strings, it automatically breaks at whitespace unless you specify otherwise.
std::string s;
std::cin >> noskipws >> s;
Alternatively, if you want to get a whole line then use:
std::getline(cin, s);
You'll also want to allocate storage for a raw char array, but with C++ you should use std::string or std::wstring anyway.
You need to allocate space for the char array into which you want to read the Name. char *Name; will not work as it only declares a char pointer not a char array. Something like char Name[30];
Also the cin << only allows us to enter one word into a string (char name[30]).
However, there is a cin function that reads text containing blanks.
cin.get(name, MAX)
get will read all characters including spaces until Max characters have
been read or the end of line character (ā€˜\nā€™) is reached and will put them
into the name variable.
You just declared a character pointer that doesn't point at anything. You need to allocate space for your string. The most common method would be to allocate space on the stack, IE:
char Name[50];
Remember a char pointer by itself is just a place to put an address to where the real memory is. You still have to get a block of memory and store the address in your pointer. The code above creates an array of Names on the stack and you can use Name to store up to 49 chars plus a null terminal.
Alternatively, for variable length strings use std::string.