I have a string that contains what ever the user has input
string userstr = "";
cout << "Please enter a string ";
getline (cin, userstr);
The string is then stored in userstr, I then want the string to be stored in a integer array where each character is a different element in the array. I have created a dynamic array as the following:
int* myarray = new int[sizeof(userstr)];
However how do I then get my string into that array?
You can access each element in your string using the [] operator, which will return a reference to a char. You can then deduct the int value for char '0' and you will get the correct int representation.
for(int i=0;i<userstr.length();i++){
myarray[i] = userstr[i] - '0';
}
int* myarray = new int[ userstr.size() ];
std::copy( usestr.begin(), userstr.end(), myarray );
The terminating zero was not appended to the array. If you need it you should allocate the array having one more element and place the terminating zero yourself.
You can just simply use isstringstream to convert the string to int as follows
istringstream istringName(intString);
istringName >> real_int_val;
now it has magically become a int containing all numbers from string
However I do not see why you would not cin it as a int in the first place??
Here is one way to do it
for(int i=0;i<userstr.length();i++){
myarray[i] = userstr[i];
}
Related
I am learning c++, I write some code to convert a string to uppercase and display it. I assign a string str with "asdf" and then create a char array pointer and allocate a length same as that of the string.
But after I assign indices of char array with uppercase chars when I try to display char array there are many junk characters appended to the end. Why does this happen as I have only allocated the char array with a size = "length of string" then how does char array have junk chars at the end even after the actual allocated size.
string str{ "asdf" };
char* str_c = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
str_c[i] = toupper(str[i]);
}
cout << str_c; // displays ASDF²▌r┐│w²A∙
Your char array needs to be one character longer than the length of the string, for the null terminator
string str{ "asdf" };
char* str_c = new char[str.length() + 1];
for (int i = 0; i < str.length(); i++) {
str_c[i] = toupper(str[i]);
}
str_c[str.length()] = '\0';
cout << str_c; // displays ASDF
In C-style strings (char*) the length of the string is not stored in memory. Thus, it must use some other way to determine where the string ends. The way it does that is by assuming that the string is all the bytes until the byte that is equal to zero (so-called null-terminator).
Without explicitly allocating an extra byte for the null terminator, and setting it, your string continues with the garbage that happens to be after the bytes you have allocated until it encounters (accidentally) the nearest 0.
I tried to create a code that reverse a string, I think my loops logic is correct. But I don't know what is wrong.
#include <iostream>
int main(){
std::cout<<"How many letters does your string have >> ";
int nbre;
std::cin>> nbre;
int a;
a=nbre-1;
char normal[a]={};
char reverse[a]={};
std::cout<<"Enter your string >> ";
std::cin >> normal;
for (int i=0;i<=a;i++){
normal[i]=reverse[a-i];
}
std::cout << "The reversed string is >> " << std::endl;
for (int u=0; u<=a; u++){
std::cout<<reverse[u];
}
return 0;
}
enter image description here
You have to use constant to declare an array this way:
char normal[a]={};
char reverse[a]={};
You can allocate memory like this instead:
char* normal = (char*)calloc(a+1, sizeof(char));
char* reverse = (char*)calloc(a+1, sizeof(char));
and free it once done using it.
The +1 is because you have to account for the ending null char.
I don't think letting the user account for it is a good idea unless your users will only be C-programmers... Better change a = nbre-1; to a=nbre;.
Finally, you should have meant to write your for-loop as:
for (int i = 1; i <= a; i++) {
reverse[i-1] = normal[a - i];
}
I made many changes to your for loop. I will let you do the Homework to understand why.
Personally, I would load the input string into a char array and iterate backwards, starting at the end of the input array and just doing some index math.
Let n = input string length
Iterate from i = n-1 to 0, and load input[i] into reversed[n-i]. Luceion is correct; you're not doing the correct method of actually reversing input string in the first for loop.
Trying to fill an array using a pointer so each index of array contains its' index. The output I am currently getting is this +DD;D;DD. Could someone explain where I am going wrong on this? Thanks.
#include <iostream>
using namespace std;
int main()
{
int NUMBER_ELEMENTS;
cout << "Enter number of elements: ";
cin >> NUMBER_ELEMENTS;
short array1[NUMBER_ELEMENTS];
short *arrPtr;
arrPtr = array1;
short i = 0;
while(i < NUMBER_ELEMENTS)
{
*arrPtr = i;
arrPtr = arrPtr + 1;
cout << "+" + array1[i];
i++;
}
}
Problem 1: The length of an automatic array can not be given at runtime. It must be known at compile time. In order to create an array with dynamic length, you can use std::vector instead.
explain how this is a variable length array?
You can input different values in different executions of the program. Therefore the length varies. Even the value staying the same is by itself not sufficient. The expression used the array length must be a compile time constant expression.
Problem 2: "+" + array1[i] doesn't do what you probably think it does.
The string literal is an array of characters. array1[i] is an integer. When you add an integer to an array using the plus-operator, the array decays to a pointer to first element of the array, and the the pointer is incremented by number given as the operand.
Therefore "+" + 0 increments the pointer by zero places, so the string printed in the first iteration is "+". "+" + 1 increments the pointer by one places. After the + character, there is only the null terminator, so the printed string is empty. After that iteration, the later iterations overflow the array, and the behaviour of the program is undefined.
char ** ptr = new char *[3];
ptr[0] = new char [5];
ptr[1] = new char [6];
ptr[2] = new char [7];
cout<<"Enter first array: ";
cin.getline(ptr[0], 5);
cin.getline(ptr[1], 6);
cin.getline(ptr[2], 7);
for (int i=0; i<3; i++){
cout<<ptr+i<<endl;
}
for (int i=0; i<3; i++){
delete[] ptr[i];
}
When I run this code, it gives the following output:
Enter first array: name
0xf99c20
0xf99c28
0xf99c30
I actually wanted the user input printed out.
Could someone please tell me how to do this?
The type of ptr+i is char**, not char*, so is just being printed as a pointer. To have it print as a string, use ptr[i], which is a char*.
That said, use a std::vector<std::string>. Then you can use the string version of std::getline. Then you avoid many possible problems with matching up new and delete, leaks, dealing with longer user input, dealing with a different number of lines of user input, etc.
Also, please reconsider your use of what are often considered bad practices: using namespace std; and endl (those are links to explanations).
you have logic misunderstanding of pointer concept when you print ptr+i it will give you the actual address locations of your inputs in the memory
to print the value of pointer you can use:
*(ptr+i)
or :
ptr[i]
also getline (char* s, streamsize n ); max stream size of your inputs should be bigger because there is a null character '\0' at the end of each character sequences and newline character '\n' when you enter another input:
cin.getline(ptr[0], 10);
cin.getline(ptr[1], 10);
cin.getline(ptr[2], 10);
link to the solution:
https://ideone.com/maSOSs
So I found this code on the internet, but as I'm not that familiar with C++. I found difficult to understand this: how does a vector suddenly becomes a matrix?
int main(){
int n;
string v[MAX];
cin >> n;
for(int i=0;i<n;i++)
cin >> v[i];
for(int i=0;i<n-1;i++){
int y1,y2;
y1=v[i].size();
y2=v[i+1].size();
for(int j=0; j<y1 && j<y2 ;j++)
if(v[i][j]!=v[i+1][j]){ // here <-
int x1,x2;
x1=(int) v[i][j]-'A';
x2=(int) v[i+1][j] - 'A';
m[x1][0]=true;
m[x2][0]=true;
m[x1][x2+1]=true;
break;
}
}
string v[MAX];
is an array of std::string (presumably - this is one reason to avoid using namespace std;. How do I know what type of string it is?).
You can access elements of an array with []:
int someInts[5];
someInts[3]=1000; // sets the 4th int (counting starts from 0)
You can also access characters in a std::string with []:
std::string name("chris");
std::cout << name[3]; // prints 'i'
So you can access the letters in an array of std::strings with two sets of []:
std::string names[10]; // 10 names
names[3] = "chris"; // set the 4th name
std::cout << names[3][1]; // prints 'h'
// ^ access letter in string
// ^ access string in array
Here is a self-explanatory example
int main()
{
std::string name;
name = "test";
for(int i = 0; i<4; i++)
std::cout<<name[i]<<std::endl;
std::cout << "Hello, " << name << "!\n";
}
It will print
t
e
s
t
Hello, test!
So, an array of strings is actually a 2D array of characters, that you called a matrix.
string v[N] is an array of string, string itself is an array of chars.
Since, as the commentor pointed out, there are neither vectors or matrices in the code you gave, I'll make a couple assumptions:
By "vector", you mean "array"
You think that double square brace operators ([][]) indicate a matrix.
If those are both true, I can explain what you're seeing:
string[5] strings = { Some Strings... }
//The first string in the array
string string1 = strings[0];
//The first letter of the first string
char char1 = string1[0];
//The above is the same as:
char char1Again = strings[0][0];
In the line above, the first square bracket operator returns the first string in the array. The second square bracket operator is then applied to that string, which returns the first character of that string.
This works because both arrays and Strings (which are really arrays themselves deep down) implement the square bracket operator to access their internal elements by index.
Technically, in a convoluted way, you could call this a matrix, but "2D array of characters" would be more appropriate.