I want to get one character from cin.get() and add it to a array character. I use strcat but the single character has an error. please help me if you know. thanks for all answers.
void main (void)
{
char e[80]="hi";
char c;
cin.get(c);
strcat(e,c);
cout << "e: " << e << endl;
getch();
}
This is part of my code that I want to do this.
stncat() concatenates two strings, method signature looks like this,
char * strncat ( char * destination, const char * source, size_t num );
but you are trying to concatenate a char which is not right!
As you are using C++, it is safe and easy to do it in C++ style rather than using C style.So use
std::string cAsStr(c); // Make the string
e += aAsStr; // + operator does the concatenation
If you are desperate to do it in the C style, use:
char cAsStr[] = { c, '\0' }; // Making a C-style string
strcat(e, cAsStr); // Concatenate
Change strcat(e,c) to strncat(e, &c, 1)
A little change to your code would do it.
char e[80]="hi";
char c[2] = {0}; // This is made as an array of size 2
cin.get(c[0]); // Character is read into the first position.
strcat(e,c);
cout << "e: " << e << endl;
char s[] = { c, 0 };
strcat(e, s);
But please, just use std::string:
string e="hi";
char c;
cin.get(c);
e += c;
cout << "e: " << e << endl;
Related
I am trying to convert an integer to a char pointer as shown below. The data results are different. I am not sure what is going wrong. Please help me in correcting the code.
int main(){
char *key1 = "/introduction";
std::ostringstream str1;
str1<< 10;
std::string data=str1.str();
std::cout <<"The data value="<<data<<std::endl; // The data value= 10
char *intro= new char[data.length()+1];
strcpy(intro, data.c_str());
std::cout <<"The data value="<<*intro <<std::endl; // The data value=1
return 0;
}
I am not sure why two data value are printed different i.e, 10 and 1.
In C++, when trying to print all the contents of a char * with cout, you should pass the pointer, i.e. cout << intro << endl.
What you've done here is dereferenced the char *, so cout << *intro << endl is equivalent to cout << intro[0] << endl, which is equivalent to printing the first character, 1.
I want to convert char array to structure but while printing I am getting following output
output: Test World (in line1)
st World(in line 2)
#pragma(1)
struct MyStruct
{
char a[2];
char b[5];
};
int main()
{
char test[11] = "Test World";
char *c = test;
struct MyStruct *Test = (MyStruct*)(c);
cout << Test->a << endl;
cout << Test->b;
cin.ignore();
return 0;
}
I want the output according to the size of the structure variable.
My expected output: Te (in line 1)
st wo (in line 2)
You have several problems with your program.
Firstly, you indirect through a MyStruct pointer which doesn't point to a MyStruct (nor compatible) object. Therefore the behaviour of the program is undefined.
Secondly, the string Te simply does not fit into MyStruct::a because there is not sufficient space. The string Te contains three characters, and MyStruct::a is only 2. Only the characters are T and e fit, but there is no room for the null terminator character, so it cannot be a null terminated string. The same problem is with your expectation of what fits in MyStruct::b.
Maybe it was your intention to not have a null terminated string, but then your problem is that you insert the non-null-terminated character array into the standard stream std::cout, which requires the argument to be a null terminated string. As a result of violating this requirement, the behaviour of the program will be undefined.
Here is one possible snippet that would have well defined behaviour and would have the desired output:
MyStruct Test;
std::memcpy(&Test, test, sizeof Test);
for(char c : Test.a)
std::cout << c;
std::cout << '\n';
for(char c : Test.b)
std::cout << c;
C strins are zero terminated. So you need to add terminating zeroes to the fields of the struct. https://godbolt.org/z/kfsioP
struct MyStruct
{
char a[2];
char b[5];
};
int main()
{
char test[11] = "Test World";
char *c = test;
struct MyStruct *Test = (MyStruct*)(c);
Test -> a[sizeof(Test -> a) - 1] = 0;
Test -> b[sizeof(Test -> b) - 1] = 0;
std::cout << Test->a << std::endl;
std::cout << Test->b;
return 0;
}
im trying to open a folder which I do use as a database and in the inside there should be even more folders that contain various text files.
So here's the question, how do I add two chars together so I can create a folder inside my desired folder from my input?
void registracija() {
system("cls");
char usr_temp;
cout << "________________________REGISTRACIJA________________________" << endl;
cout << "REGISTRACIJA: NORINT UZSIREGISTRUOTI, JUMS REIKES SUGALVOTI" << endl;
cout << "REGISTRACIJA: SLAPYVARDI, SLAPTAZODI BEI KLAUSIMA" << endl;
cout << "REGISTRACIJA: KURIS BUS NAUDOJAMAS GRAZINTI PAMIRSTAM SLAPTAZODZIUI!" << endl;
cout << "NORIMAS SLAPYVARDIS: ";
cin >> usr_temp;
const char temp = usr_temp;
char dirname1[] = "Vartotojai/" + usr_temp;
char *dirname = dirname1;
int check = _mkdir(dirname);
if (!check) {
cout << "TESIAME REGISTRACIJA";
}
else {
cout << "REGISTRACIJA: TOKS SLAPYVARDIS JAU YRA! REGISTRUOKITES IS NAUJO!";
system("pause>nul");
}
}
Faults I get:
Se cannot convert from 'const char *' to 'char []' ConsoleApplication1
Thanks for the answers.
Use std::string instead of cstring. cstrings can't be concatenated with operator+. You need std::strcat for cstrings. You also need to reassign memory if you want to use cstrings. It's much easier with std::string
Change
char usr_temp;
char dirname1[] = "Vartotojai/" + usr_temp;
char *dirname = dirname1;
to
std::string usr_tmp;
std::string dirname1("Vartotojai/");
dirname1 += usr_temp;
const char *dirname = dirname1.c_str();
Remove the line with char_temp. You have to include string. std::string is a container for characters. You can easily append new characters without managing memory.
I think you need to do this.
string dirname1 = "Vartotojai/" + string(1,usr_temp);
char *dirname = (char*)dirname1.c_str();
// char *dirname = const_cast<char*>(dirname1.c_str());
As you have tagged it C++, use string type instead of char array and char pointer.
I want to pre-append a character to a string after performing some calculations to the character ascii code but doing (somenumber+'0') + s doesn't work and I don't understand why.
the answer I want is "ahello" using the ascii representation of a ('0' + 49)
This is what I have tried:
std::string s = "hello";
s.insert(0, std::to_string('a'));
std::cout << s << std::endl; // 97hello
s = "hello";
s += 'a';
std::cout << s << std::endl; // helloa
s = "hello";
s = 'a' + s;
std::cout << s << std::endl; // ahello
//s = (49+'0') + s;
//std::cout << s << std::endl;
Do you want to append the ASCII code int of the character (97) or do you want to append the ASCII representation ('a') ?
In the later case, you could just use s.insert(0, "a") directly.
If you want to transform the ASCII code int before, you can use the std::string fill constructor, as was already pointed out by Steephen:
// fills the string with n consecutive copies of character c.
std::string(size_t n, char c);
// so you could do this to get a string "f":
std::string(1, 'a'+5);
This will solve the issue:
s.insert(0, string(1,1+'a'));
O/p
bhello
s.insert(0, string(1,0+'a'));
O/P
ahello
Try
s.insert(0, string(1,49+'a'));
I am a c++ beginner and I am struggling to produce a program for the following assignment:
Create a project called “StringLength”. The main program should include a function (called findStringLength) which will calculate the length of a string (that is, the number of characters in the string, excluding the terminating null character).
The main program should test the operation of the function with the following test strings:
"Short string"
"A longer string used for test purposes"
""
" "
Declare four character arrays and assign these test values. The output of the program should take the form shown below for each test string:
Length of "Short" = 5
You should write the code to calculate the length of the string yourself; do not use any of the library functions to do this.
Note that if a quotation mark " is to be included in the string, it should be preceded by a backslash \ character – to prevent it from being interpreted as the end of the string:
"Quotation char \" in string"
will be displayed as:
Quotation char " in string
My code is as follows:
#include <iostream>
using namespace std;
size_t findStringLength (char*);
int main()
{
char n1[] = "Short string";
char n2[] = "A longer string is used for test purposes";
char n3[] = "";
char n4[] = " ";
int stringlength;
stringlength = findStringLength("Short string/");
cout << "Length of " << n1 << " = " << stringlength << endl;
stringlength = findStringLength("A longer string used for test purposes/");
cout << "\nLength of " << n2 << " = " << stringlength << endl;
stringlength = findStringLength("/");
cout << "\nLength of " << n3 << " = " << stringlength << endl;
stringlength = findStringLength(" /");
cout << "\nLength of " << n4 << " = " << stringlength << endl;
cout << "\n";
}
size_t findStringLength (char string[])
{
int i=0;
while(string[i])i++;
return i;
}
EDIT I now have the code shown above, which gives the correct output to a certain extent. Problem being I receive this
error:H:\StringLength\main.cpp:16: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
stringlength = findStringLength("Short string/");
^
I would recommend a simple while loop instead:
int string_length = 0;
while (input_str[string_length] != '\0') { string_length++; }
return string_length;
It iterates along the string until it hits a null character.
The function can be written in many ways. For example
size_t findStringLength( const char *s )
{
size_t n = 0;
while ( s[n] != '\0' ) ++n;
return n;
}
Take into account that you call the function for character arrays (as it is described in your assignment). So your function declaration
char findStringLength (char);
is wrong because the parameter is not declared as a character array or a pointer to first element of a character array. Also you specified a wrong return type.
These two function declarations are equivalent
size_t findStringLength( const char s[] );
size_t findStringLength( const char *s );
I would like to answer the following doubt of yours
I also receive a repetitive error in conversion from char* to char.
=> that's actually the error you are getting because of the way you are passing your string to the function which is declared as:
char findStringLength (char);
and what you are passing is actually n1,n2,etc which are actually arrays of type char and not the character string itself.you should read more about passing of arguments to functions in c++ and for this case you have to pass it by value so better declare your function as:
char findStringLength (char*);
int findStringLength (char string[])
{
int i=0;
while(string[i])i++;
return i;
}