Need to access an element from part of a string array - c++

Suppose I have this code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string disectedString[5];
disectedString[0] = "011001";
string temp = disectedString[0];
string print = temp[0];
return 0;
}
So I'm selecting an element out of my array of strings, and then assigning it to a temp variable. From there, I want to select the first element out of the temp variable,(the first character). How would I go about doing this?

Your intuition is mostly valid: You use the square brackets operator, [], to access the element at an indexed position within a collection or sequence. Thus
disectedString[0] means "the first element of disectedString";
temp[0] means "the first element of temp";
What you've gotten mixed up are the types, as commenters and #demogorgon.net's answer have explained.
Now, with modern C++ you can "play dumb" and not declare what you know the types to be:
std::string disectedString[5];
disectedString[0] = "011001";
auto temp = disectedString[0];
auto print = temp[0];
Note the use of auto instead of a specific type name. This will work as you would like it to. You can then use use print, and do, for example:
std::cout << print;
and this will output 0.
By the way, I believe you should reconsider your choice of names:
Intuitively, print should refer to a function, or a method, which prints things; I'd suggest first_character or char_to_print or just c if you want to be brief.
temp is no more a temporary variable than, say, print.
It's better to avoid variable names which contain the type name, although we sometimes sort of have to resort to that. Specifically you using the word 'string' in variable names; probably not a good idea.
Your disectedString variable is not a string, it's an array of strings, which is confusing.

A string behaves in many ways like an array of char's (*). You need to set print to char type instead of string since you are trying to get a specific element from the string. So your print should look like this:
char print = temp[0];
(*) but it's really more complicated than that.
Here is a code example that prints the output.

Related

Problem in comparing strings without assigning to variable

int i = ("aac" > "aab");
cout << i;
The above code does not give me the output as 1 (as it should be). But when I assign "aac" and "aab" to two separate string variables and use the variables instead of using strings directly (code attached below), I get the desired output.
Could anyone help me please?
string s1 = "aac";
string s2 = "aab";
int i = (s1 > s2);
cout << i;
Literal constants like "aac" aren't std::string objects; rather, they are just data in (read-only) memory that evaluate, in most 'access' cases, to the address of their first element (i.e. a char* pointer); so, a comparison between them will be a comparison between those addresses — something you are unlikely to be able to control or predict.
To get an inline comparison, in your case, you can use inline std::string constructors (sometimes knows as "wrappers"), like this:
int i=(string("aac")>string("aab"));
Or, using the more 'modern' "curly-brace" initializer syntax:
int i = (string{ "aac" } > string{ "aab" });
For more brevity, you can make use of the fact that std::string has versions of the > (and similar) operators that take a string literal as one of the arguments; thus, you need only 'wrap' one of the literals, and could reduce the above code to something like:
int i = (string{ "aac" } > "aab");
If you use C-style char * / char [] strings, you need to use strcmp like:
int i = strcmp("aac", "aab");
Otherwise, you are just comparing addresses of the first elements of both of strings.

How do I declare a new string the same length of a known const string?

I've been using:
string letters = THESAMELENGTH; // Assign for allocation purposes.
Reason being, if I:
string letters[THESAMELENGTH.length()];
I get a non constant expression complaint.
But if I:
string letters[12];
I'm at risk of needing to change every instance if the guide const string changes size.
But it seems foolish to assign a string when I won't use those entries, I only want my newly assigned string to be the same length as the previously assigned const string, then fill with different values.
How do you recommend I do this gracefully and safely?
You can
string letters(THESAMELENGTH.length(), ' '); // constructs the string with THESAMELENGTH.length() copies of character ' '
BTW: string letters[12]; doesn't mean the same as you expected. It declares a raw array of string containing 12 elements.
I only want my newly assigned string to be the same length as the previously assigned const string, then fill with different values.
Part of the reason the string class/type exists is so you don't have to worry about trying to manage its length. (The problem with arrays of char.)
If you have a const std::string tmp then you can't just assign anything to it after it has already been initialized. E.g.:
const std::string tmp = "A value"; // initialization
tmp = "Another value"; // compile error
How do you recommend I do this gracefully and safely?
If you really want to keep strings to a specific size, regardless of their contents, you could always resize your string variables. For example:
// in some constants.h file
const int MAX_STRING_LENGTH = 16;
// in other files
#include "constants.h"
// ...
std::string word = ... // some unknown string
word.resize(MAX_STRING_LENGTH);
Now your word string will have a length/size of MAX_STRING_LENGTH and anything beyond the end gets truncated.
This example is from C++ Reference
// resizing string
#include <iostream>
#include <string>
int main ()
{
std::string str ("I like to code in C");
std::cout << str << '\n';
unsigned sz = str.size();
str.resize (sz+2,'+');
std::cout << str << '\n';
str.resize (14);
std::cout << str << '\n';
return 0;
}
// program output
I like to code in C
I like to code in C++
I like to code
You can't just ask a string variable for its length at compile-time. By definition, it's impossible to know the value of a variable, or the state of any given program for that matter, while it's not running. This question only makes sense at run-time.
Others have mentioned this, but there seems to be an issue with your understanding of string letters[12];. That gives you an array of string types, i.e. you get space for 12 full strings (e.g. words/sentences/etc), not just letters.
In other words, you could do:
for(size_t i = 0; i < letters.size(); ++i)
letters[i] = "Hello, world!";
So your letters variable should be renamed to something more accurate (e.g. words).
If you really want letters (e.g. the full alphabet on a single string), you could do something like this:
// constants.h
const std::string ALPHABET_LC = "abc...z";
const std::string ALPHABET_UC = "ABC...Z";
const int LETTER_A = 0;
const int LETTER_B = 1;
// ...
// main.cpp, etc.
char a = ALPHABET_LC[LETTER_A];
char B = ALPHABET_UC[LETTER_B];
// ...
It all depends on what you need to do, but this might be a good alternative.
Disclaimer: Note that it's not really my recommendation that you do this. You should let strings manage their own length. For example, if the string value is actually shorter than your limit, you're causing your variable to use more space/memory than needed, and if it's longer, you're still truncating it. Neither side-effect is good, IMHO.
The first thing you need to do is understand the difference between a string length and an array dimension.
std::string letters = "Hello";
creates a single string that contains the characters from "Hello", and has length 5.
In comparison
std::string letters[5];
creates an array of five distinct default-constructed objects of type std::string. It doesn't create a single string of 5 characters. The reason for the non-constant complaint when doing
std::string letters[THESAMELENGTH.length()];
is that construction of arrays in standard C++ is required to use a length known to the compiler, whereas the length of a std::string is determined at run time.
If you have a string, and what to create another string of the same length, you can do something like
std::string another_string(letters.length(), 'A');
which will create a single string containing the required number of letters 'A'.
It is largely pointless to do what you are seeking as a std::string can dynamically change its length anyway, as needed. There is also nothing stopping a std::string from allocating more than it needs (e.g. to make provision for multiple increases in its length).

How can I insert integer into a string using insert function in C++?

Below check is string and temp1->data is integer. I want to insert temp1->data into check. So I type cast int into const char*. This gives warning : cast to pointer from integer of different size [-Wint-to-pointer-cast]
Part of code:
temp1 = head;
std::string check;
check = "";
int i = 0;
while(temp1 != NULL)
{
check.insert(i, (const char*)temp1->data);// here is the warning
temp1 = temp1->next;
++i;
}
I want to know what other choices I have to insert the integer (temp1->data) into string(check) using insert function and what is the actual effect of warning [-Wint-to-pointer-cast] on my code.
Points:
data is integer, next is pointer to Node
I'm trying to implement a function to check if a linked list containing single digit number is palindrome or not. Yes, I know other methods for this but I just want to implement through this method too.
Here I want to store all the data of linked list into a string and directly check if the string is palindrome or not.
This question may seem duplicate of this . But it is not, here I explicitly asked for inserting integer into string using insert function contained in string class.
PS: on using std::to_string(temp1->data) gives me error ‘to_string’ is not a member of ‘std’.
You can use std::to_string function to convert integer to string and then insert it in a string using insert function on std::string.
std::string check;
check = "";
int i = 0;
check.insert(i, std::to_string(10));
The reason you are getting error "to_string is not a member of std" is may be because you did not include <string> header.
First, here's a way to convert an integer to a string without much work. You basically create a stream, flush the int into it, and then extract the value you need. The underlying code will handle the dirty work.
Here's a quick example:
stringstream temp_stream;
int int_to_convert = 5;
temp_stream << int_to_convert;
string int_as_string(temp_stream.str());
Here's more info on this solution and alternatives if you want to know more:
Easiest way to convert int to string in C++
Regarding the impact of the cast that you're doing, the behavior will be undefined because you're setting char* to an int value. The effect won't be converting the int value to a series of characters, instead you'll be setting the memory location of what the system interprets as the location of first character of a char array to the value of the int.

Character Pointers (allotted by new)

I wrote the following code:
char *pch=new char[12];
char *f=new char[42];
char *lab=new char[20];
char *mne=new char[10];
char *add=new char[10];
If initially I want these arrays to be null, can't I do this:
*lab="\0";
*mne="\0";
and so on.....
And after that if I want to add some cstring to an empty array can't I check:
if(strcmp(lab,"\0")==0)
//then add cstring by *lab="cstring";
And if I can't do any of these things, please tell me the right way to do it...
In C++11, an easy way to initialize arrays is by using brace-initializers:
char * p = new char[100] { 0 };
The reasoning here is that all the missing array elements will be zero-initialized. You can also use explicit value-initialization (I think that's even allowed in C++98/03), which is zero-initalization for the primitive types:
char * q = new char[110]();
First of all, as DeadMG says, the correct way of doing this is using std:string:
std::string lab; // empty initially, no further initialization needed
if (lab.size() == 0) // string empty, note, very fast, no character comparison
lab += "cstring"; // or even lab = "cstring", as lab is empty
Also, in your code, if you insist in using C strings, after the initialization, the correct checking for the empty string would be
if (*lab == '\0')
First of all, I agree with everybody else to use a std::string instead of character arrays the vast majority of the time. Link for help is here: C++ Strings Library
Now to directly answer your question as well:
*lab="\0";
*mne="\0";
and so on.....
This is wrong. Assuming your compiler doesn't give you an error, you're not assigning the "null terminator" to those arrays, you're trying to assign the pointer value of where the "\0" string is to the first few memory locations where the char* is pointing to! Remember, your variables are pointers, not strings. If you're trying to just put a null-character at the beginning, so that strlen or other C-string functions see an "empty" string, do this: *lab='\0'; The difference is that with single-ticks, it denotes the character \0 whereas with double, it's a string literal, which returns a pointer to the first element. I hope that made sense.
Now for your second, again, you can't just "assign" like that to C-style strings. You need to put each character into the array and terminate it correctly. Usually the easiest way is with sprintf:
sprintf(lab, "%s", "mystring");
This may not make much sense, especially as I'm not dereferencing the pointer, but I'll walk you through it. The first argument says to sprintf "output your characters to where this pointer is pointing." So it needs the raw pointer. The second is a format string, like printf uses. So I'm telling it to use the first argument as a string. And the 3rd is what I want in there, a pointer to another string. This example would also work with sprintf(lab, "mystring") as well.
If you want to get into C-style string processing, you need to read some examples. I'm afraid I don't even know where to look on the 'net for good examples of that, but I wish you good luck. I'd highly recommend that you check out the C++ strings library though, and the basic_string<> type there. That's typedef'd to just std::string, which is what you should use.

C++ Multi dimensional array from external file question

I'm trying to get a contiguous line with values separated by "&" to load into a multi-dimensional array. Here's the way I'm trying to do it - Everything checks out in the code, except the string "str" which contains my separated values in the format "value1, value2, value3, etc..." just loads that whole string into array[0][0]. I know there are better ways of doing this, but what I would like to know is why C++ won't treat "str" as if I had typed out the individual values and hard coded "array".
Here is the code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
string str, strTotal;
ifstream in;
in.open("Desktop/01_001.PAC");
getline(in,str);
while ( in ) {
strTotal += str;
getline(in,str);
}
string searchString( "&" );
string replaceString( ", " );
assert( searchString != replaceString );
string::size_type pos = 0;
while ( (pos = str.find(searchString, pos)) != string::npos ) {
str.replace( pos, searchString.size(), replaceString );
pos++;
}
string array[4][5] = {str};
cout << array[0][0];
return(0);
}
And here is the external file ("Desktop/01_001.PAC"):
void&void&void&void&a&a1&a2&a3&b&b1&b2&b3&c&c1&c2&c3&d&d1&d2&d3
Thanks in advance!
Because code and data are different things. Your code is compiled before it runs.
It sounds as if this is what you expect:
The string contains the text "foo, bar, baz".
The statement string[] whatever = {str}; is run.
Since "str" contains "foo, bar, baz", you want it to have the same effect as if the line of code were actually string[] whatever = {"foo", "bar", "baz"}.
Asking something like this implies a complete misunderstanding of how programming works.
Nothing this magical will ever happen in C++. It cannot, because (a) what if you actually wanted to put 'str' into the array? (b) what if 'foo', 'bar' and 'baz' were also variables in your program - should they be interpreted the same way?
Variable names are not text. They no longer exist, for all practical purposes, at the time that your code runs. They are only there so that you, as the programmer, can say "the value that is used over here should be the same one that is used over there".
Further, array initializations in C++ do not care how many elements are actually in the initialization vs. the declared size of the array. Any additional elements will be default-initialized (i.e., assigned empty strings).
A string cannot be treated like an array of strings, because it isn't one. If you want an array of strings, then build it, using the individual string elements as you determine them.
But since you don't know in advance how many elements there are, you should use std::vector instead of an array. And why are you trying to arrange the data into a 2-dimensional structure? How are you expecting to know how "wide" it should be?
If I'm reading your code correctly, you appear to be searching through the string (loaded from file), and only assigning the very last result to an array index (x=4, y=5). So your code is doing something like this:
while (have not found last variable)
search for next variable in string
assign variable to (4,5) in matrix
So that last assignment might even work, but since you only assign at the end, the array is not going to be filled the way I think you want it to be filled.
I'm going to assume the matrix you want is always the same size, otherwise things get more complicated. In this case, you could use something like this:
let xMax = 4
let yMax = 5
for (x from 0 to xMax)
for (y from 0 to yMax)
find the next variable in the string
assign it to the current (x,y) location in matrix
Debug statements are your friend here! Try the above solution without saving it to an array, and instead print out each term, to see if it is working correctly.
I would also point out that the string "void" is not the C++ keyword void, and so will not work if you want an array index to be void. Try getting your code to work without voids at first.