C++ , Array of strings - c++

I was just curious to know how to create an array of strings.
I am looking to make an array of 10 strings and each string can have 20 characters.
#include <iostream>
int main()
{
char a[10] , str[20];
for (int x = 0 ; x<10 ; x++)
{
for (int y = 0 ;y<20; y++ )
{
cout<<"String:";
cin>>str[y];
a[x]=str[y];
}
}
for (int j = 0 ; j<10 ; j++)
cout<<a[j]<<endl;
return 0;
}
Newbie in C++ with an open mind :)

How about instead you use a
std::vector<std::string> my_strings(10); // vector of 10 strings
You will have a much easier time this way than statically-size char arrays.
You then get all the features of the std::vector container, including dynamic size.
You also get all the nice features of the std::string class.

What are you doing is more C approach.
Anyway:
char strings[10][20];
//Accessing each string
for(int i = 0; i < 10; i++)
{
//Accessing each character
for(int j = 0; j < 20; j++)
{
char character = strings[i][j];
}
}
In c++ you would rather use:
std::string strings[10];
Or the best option is:
std::vector<std::string> strings(10);
in c++ 11 you can iterate over last case like this:
for(auto singleString : strings)
{
}

In order of preference:
A vector of 10 strings:
std::vector<std::string> aVector(10);
An array of 10 strings:
std::string anArray[10];
If you really want to use zero-terminated C strings:
typedef char MyString[21]; // 20 + 1, for the terminating zero
MyString arrayOfThem[10];
or, the more cryptic variant
char anArray[10][21];

Related

Can I store a string in character array but reverse order, such that 0(index) points to last character in string?

I started to learn to program and I'm trying to store a string into a character array but in reverse order, such that array index position 0(zero) points to the last character in the string. I tried using for loops in different terms but getting the desired output. I want to solve this problem in C++.
Here is the code that I'm stuck on,
#include <iostream>
using namespace std;
int main()
{
char str[maxn];
string entstr;
cin>>entstr;
int len = entstr.length();
cout<<len<<endl;
for(int i = 0 ; i < len ; i++) //this makes \n no sense//
for(int j = len-1 ; j >= 0 ; j--)
str[i] = entstr[j];
for(int i = len-1 ; i >= 0 ; i--)
cout<<"Straight for array "<<i<<" "<<str[i]<<endl;
return 0;
}
OUTPUT:
sachin
6
Straight for array 5 s
Straight for array 4 s
Straight for array 3 s
Straight for array 2 s
Straight for array 1 s
Straight for array 0 s
I guess you don't wanna use std::reverse mentioned in the comments because you want to practice your algorithmic skills.
You can help yourself with this short program. It uses std::malloc to allocate a char array of the size of the input string. Then, you just need to loop backward through the character of the string and store it into your array.
I recommend you to follow (write it down on a paper) the values of i and len-1-i inside the loop. It will help you to understand how index works.
#include <iostream>
using namespace std;
int main()
{
string entstr;
cin >> entstr;
int len = entstr.length();
char* charArray = (char*) malloc (len);
for(int i = 0; i < len; i++)
{
charArray[i] = entstr[len-1-i];
}
cout << "charArray contains: ";
for(int j = 0; j < len; j++)
{
cout << charArray[j];
}
return 0;
}
Good luck!
I don't think there is any use for two loops. Just start the string from the front and your array from len-1 (just the way you did in the for loop for printing). You can take whatever length you want your char array to be.
#include <iostream>
using namespace std;
int main()
{
char str[100]; //put whatever you want the length of the char array to be
string entstr;
cin>>entstr;
int len = entstr.length();
cout<<len<<endl;
for(int i = 0 ; i < len ; i++)
{
str[len-1-i]=entstr[i];
}
for(int i = len-1 ; i >= 0 ; i--)
cout<<"Straight for array "<<i<<" "<<str[i]<<endl;
return 0;
}
You can use two pointers too for the same i.e. one starting from the front and one from the end (if you get confused)
for(int i = 0, j=len-1 ; i < len ; i++, j--)
{
str[j]=entstr[i];
}

How to Intialise on double pointer char array like below?

I'm searching to initialize data of char type like below. but I'm not sure on how to do this
char* data[ ][ ] = {
{"", "index1", "clock1", "Rate1"},
{"", "index2", "clock2", "Rate2"},
{"", "index3", "clock3", "Rate3"},
{"", "index4", "clock4", "Rate4"}
}
so that when I want to assign data of above table to other variables like below
for( int i = 0; i < 6; i++)
{
char k[][];
for(int j = 0; j < 6; j++ )
{
k[i][j] = data[i][j];
}
}
and my expected output is like this
k[i][1] = "index1", k[i][2] = "clock1", k[i][3] = "Rate1"
k[i+1][1] = "index2", k[i+1][2] = "clock2", k[i+1][3] = "Rate2" etc.,
How could I initialize the variable data like above to get the values like mentioned in output?
A couple things to note in the k assignment loop. You are looping 0-6 when the array bounds defined in data are 0-3 (4 elements). You initialized k within your for loop. k will need bounds because it is not being initialized. Remember, arrays in C are of a fixed size. Here is the code I'm referring to:
for( int i = 0; i < 6; i++)
{
char k[][]; /* Re-initialize here? */
for(int j = 0; j < 6; j++ )
{
k[i][j] = data[i][j];
}
}
k will need to be initialized with bounds like this:
char* k[4][4];
Also, your assignment of data is not doing what you think it is. You want to initialize it like this:
char* data[4][4] = {
{{""}, {"index1"}, {"clock1"}, {"Rate1"}},
{{""}, {"index2"}, {"clock2"}, {"Rate2"}},
{{""}, {"index3"}, {"clock3"}, {"Rate3"}},
{{""}, {"index4"}, {"clock4"}, {"Rate4"}}
};
In reality though, this also is not going to be very helpful because, as I said above, arrays are of fixed size. Elements data[0][x] are all single element arrays of char. They will serve no purpose. I think you want to assign different strings to them. Assigning/accessing data[0][x][y] where y is greater than 0 will be undefined behavior. It looks like what you really need here is variable length strings. Since you tagged this question with C++, an easy C++ solution would be to use std::string here. If you really need totally variable length strings in C, you will need to use dynamic memory allocation. For a more simple approach, it would be better to assign data with a fixed string size. Later, if you want to assign different strings, you will want to use strcpy.
Below is a solution for you. I used 20 as the fixed string size. You may want more space.
#include<stdio.h>
int main(int argc, char** argv)
{
char data[4][4][20] = {
{{""}, {"index1"}, {"clock1"}, {"Rate1"}},
{{""}, {"index2"}, {"clock2"}, {"Rate2"}},
{{""}, {"index3"}, {"clock3"}, {"Rate3"}},
{{""}, {"index4"}, {"clock4"}, {"Rate4"}}
};
int i;
int j;
char* k[4][4];
for(i = 0; i < 4; i++)
for(j = 0; j < 4; j++ )
k[i][j] = data[i][j];
for (i = 0; i < 4; ++i)
for(j = 0; j < 4; ++j)
printf("%s\n", k[i][j]);
}

Get string content from string pointer C++

so I'm working on a project that I have to read contents from a file and then analyze them. But I'm having a problem with getting the string out of a pointer that contains the address to what I need.
string lePapel(vector<char> vec){
string *str, s;
int i, j = 0;
vector<char> aux;
aux.resize(6);
for (i = 57; i <= 62; i++){
aux[j] = vec[i];
j++;
}
str = new string[aux.size()];
for (i = 0; i < 6; i++){ str[i] = aux[i]; }
return s;
}
So, the file contains in the array positions from 57 to 62 the word: ABCB4, but when returning the string s my output is A only as expected because of the pointer.
The thing is that I have been trying to find a solution and storing the whole content from vec[57] to vec[64] into the string s and returning it, and the closest that I got to returning anything plausible was using a pointer.
So, now to my question, how can I iterate the *str pointer and copy the whole content to s and return it?
Thanks in advance
I'd suggest you to not use pointers on string in your case. The following code is probably what you want :
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string lePapel(vector<char> vec){
int j = 0;
vector<char> aux;
aux.resize(6);
for (int i = 57; i <= 62; i++){
aux[j] = vec[j];
j++;
}
string str;
str.reserve(6);
for (int i = 0; i < 6; i++){ str.push_back(aux[i]); }
return str;
}
int main() {
char x[5] = {'A', 'B', 'C', 'B', '4'};
vector<char> vec(x, x + 5);
string s = lePapel(vec);
cout << s;
return 0;
}
Tested here : Tested code
About reserving space to your vector : c++ vector::reserve
Same for strings : reserve for strings
The dynamic array of string objects and the whole aux vector seem completely needless here (unless there's some other purpose for them in your code). Additionally, str is currently causing a memory leak because you never delete it when you're finished.
A much simpler approach is just to append the characters one-at-a-time to the s string object (assuming it's a std::string):
string lePapel(vector<char> vec) {
string s;
for (int i = 57; i <= 62; i++) {
s += vec[i];
}
return s;
}
There are various ways to make the code even shorter (and more efficient) than that though, if you really want to.
EDIT: If you still need/want to iterate your dynamic array and concatenate the contents into s, here's how you could do it:
for (i = 0; i < 6; i++) s += str[i];
delete [] str; //<-- very important!
Short answer, you don't want a string * you want a char *. What you created is a string array. String objects contain a pointer to the char * data you are trying to capture. Also, the sizeof(std::string) (8 bytes in size) is a lot bigger than sizeof(char) (1 byte in size) the second character you store is 8 bytes away from the first character instead of being adjacent.
There are a lot of other C++ style and safety concerns, but I'll stick with the question. ;)

Writing a loop to change the value in a int array with different names

My title is a bit confusing, but I'm trying to write a loop that will change the value in 81 arrays with different names. I want to either initiated the array with a value or an array of values. This is part of my sudoku solver code since I don't think I'm explaining it well.
int cell1[], cell2[9], cell3[9],cell4[9]......cell81[9]; // <-- this will make 81 cells with an array that can hold a possible of 9 candidates
cout << "User input: << endl; // lets use ...1.5...14....67..8...24...63.7..1.9.......3.1..9.52...72...8..26....35...4.9...
// as an example
Let's assume I store that input into a Char Array and I'm going to use a loop to decide whether to initiate the given value or '.' as an empty value.
For empty values, I'm looking to initialize the array with 1-9 values. I can do this easily with this code.
If( ( (int)charArray[ 0 ] - 48) > 0 ) { // type cast to int. Neg = initialize array with 1-9
// pos = initialize with original value
cell1[ 0 ] = (int)charArray[ 0 ] - 48;
} else {
cell1[ 9 ] = { 1,2,3,4,5,6,7,8,9};
}
I want to avoid writing this code 81 times for 81 cells ( Considered as writing junk code ). I can't figure out how to write the loop. I'm open to suggestions on how I can code this different using classes, functions, and etc. Thanks in advance.
Create the cell array as a 2-dimensional array, with 81 rows and 9 columns.
int cell[81][9];
Now you can loop through them using the syntax cell[r][c]. For instance,
for( i = 0; i < 81; ++i ) {
cell[i][0] = 1;
// ...
cell[i][8] = 9;
}
If you'd prefer to avoid 2-D arrays, you can declare the array as a 1-dimensional array, and just index into it appropriately.
int cell[81 * 9];
for( i = 0; i < 81; ++i ) {
cell[i + 0*81] = 1;
// ...
cell[i + 8*81] = 9;
}
int a1[9],a2[9],a3[9],a4[9],...
void init_array(int *ptr, const char *chr, int len, int start){
for(int i = start; i < len; i++){
if(chr[i] == '.')continue;
ptr[i] = chr[i]-'0';//converts character to integer.
}
}
int main(int argc, char **argv)
{
std::string str;
cin >> str;
init_array(a1,str.c_str(),9,0); init_array(a2,str.c_str(),9,9/*increment by 9*/);...
//..
return 0;
}
Write a function called init_array() that accepts an integer pointer and initializes the array for you. You can avoid duplicating the code this way.

How to use vector<string> in OCCI setDataBuffer?

I have a simple table called mytable2 with only one column, name as varchar2(20).
I now have a list of names stored as vector of std::string to be inserted into the table.
I want to use executeArrayUpdate, so I must do the setDataBuffer first.
However, as I could see, people always use char[][20] to set databuffer.
This leaves me a big headache, since I have two issues here, first is to convert from vector to array, second is to convert the string to char.
1st, I tired to use vector of char[20], and this doesn't compile. Googled and they say that vector can't take char[], so I changed my vector of std::string to vector of char*.
2nd, I tried to turn the vector to arrray by using "void* p=&names[0]", as some people say this way we can use vectors just as array.
I used stmt->setDataBuffer(1,mystring,OCCI_SQLT_STR,20,NULL), and the program compiled and executed alright, but when I "select name from mytable2", it showed only some strange charaters.
Anyone has had a similiar issue before? what should I do?
My code is simple as below:
count=2;
vector<char*> mystring;
for(int i=0;i<count;i++)
{
char my[20];
strcpy_s(my,"Michael");
mystring.insert(mystring.end(),my);
}
stmt->setDataBuffer(1,&mystring[0],OCCI_SQLT_STR,20,NULL);
stmt->setBatchErrorMode (true);
stmt->executeArrayUpdate(count);
You'd need to dynamically create the char array you're putting into the vector for it to have a chance of working correctly.
I have not used OCCI, but if I had to use API that asked for char[][20], I would give it char[][20]
If you have your existing data in vector, why not just copy it across into the 2D char array? Eg.
// intialise vector with nonsense
unsigned int const VEC_SIZE = 2 ;
vector<string> v;
for (unsigned int i = 0; i < VEC_SIZE; ++i) {
stringstream s;
s << "Jon Paul " << i << endl;
v.push_back ( s.str() ) ;
}
// create the required 2D char array
unsigned int const STR_LEN = 20 ;
char c [VEC_SIZE][STR_LEN];
// copy the data from the vector of strings to the 2D char array
for (unsigned int i = 0; i < VEC_SIZE; ++i) {
string s = v[i].substr(0,STR_LEN);
char const * const cc = s.c_str();
unsigned int j = 0;
for (; j < STR_LEN && j < s.size(); ++j) {
c[i][j] = cc[j];
}
c[i][ j==STR_LEN ? 20 : j ] = 0; // write NULL character
}
I take it you've simplified your example to be a fixed size vector, so my response is going to be simplified to, with the thorny issue of dynamic allocation of 2D arrays left as an exercise for the reader...