Is it possible to initialize characters to a number, n, based on how many characters the user inputs? - c++

I had a homework question where I had to ask the user for a character and use that character to create the image of the letter C. It sparked an interest and I wanted to try and make a program that asks the user for a letter, word, or sentence of their choice and have it create the letter, word, or sentence out of a character they choose. For exmaple if the user inputs "Hi" with the character X, the out put would be:
X X X
X X
XXXX X
X X X
X X X
This is probably beyond my league because I'm a newbie to c++ and coding in general, however I enjoy messing around with code so its something I wanted to try.
My idea is to make a switch statement that loops through every letter and replaces each letter with the corresponding letter output. However I can't figure out how I would initialize the infinite amount of possible characters the user inputs.
Is there a way to make the input a string and then translate the string into individual char types? From then I can just loop through each character and use the switch statement to switch it out. Also is there a way to count how many characters there are so I can use that to make the loop? For example in python I could just use len("string") and it would give an integer value. Is there anything like that in C++?
I know there is probably a lot simpler and cleaner ways to go about this project, but I'm very limited to the little knowledge I know right now.
Any input would be awesome, thanks.

Is there a way to make the input a string
Yes, and it sounds like you already know how to do this part.
and then translate the string into individual char types?
Yes, if str is a variable holding the string, and i is the index of the character you want to get, then str[i] is that character. (Remember the first character is at index 0)
Also is there a way to count how many characters there are so I can use that to make the loop?
Yes, if str is a variable holding the string, then use str.length() (assuming it's a string rather than a C-style array of characters).
For example in python I could just use len("string") and it would give an integer value. Is there anything like that in C++?
See above.

Related

Rocket Universe string delete a character question

This one has me wondering if I may be missing a function or something.
Have a string, example TZ118-AH01
I simply want to remove the second character and was wondering if there was a simple way of doing this, cannot use CONVERT as the second character may be repeated in the string.
Currently figuring I have to something like
VALUE = STRING[1,1]:STRING[3,LEN(STRING)-2]
Which seems a bit cumbersome.
Anyone have a nifty work around?
VALUE = STRING[1,1]:STRING[LEN(STRING)-2]
Would be syntactically the same if you are sure that the length won't ever be less that 2, and if for some reason it does you don't mind stopping the entire call stack.
If the first and second characters are known commodities, you could use field and fudge up the field count in the forth variable to something high like 1000, but that is kludgy and relies on the first and second character not being the same.
The best was would be a function or subroutine to concatenate a new new string iterating through the character array and skipping the second iteration.
SUBROUTINE Remove2ndChar(StringOut,StringIn)
StringOut=""
CC=LEN(StringIn)
FOR C=1 TO CC
If C NE 2 THEN
StringOut:=StringIn[C,1]
END
NEXT C
RETURN
This is not necessarily what you are looking for, but it is probably going to be more execution safe.
Good Luck.

Getting an integer value from string in c++

I am trying to learn c++, and for an assignment I have ran into a problem. I am trying to get an integer value from a string that a user enters all on one line.
Ex.) The user inputs: "Change value to 15."
What is the best way of getting the 15 from that string? I have looked around for a while, but could only find if a string was only integers.
Thanks in advance!
Why not use a mixture of getline(grabs your whole line) and string stream(tokenizes the input) and put them all in a vector(easier to use than an array), grab the one at .size()-1 and do an atoi on that. Might be overkill, but string stream could do what you want. For a small tut this could help http://www.dreamincode.net/forums/topic/95826-stringstream-tutorial/
This might not be the best way but to get something done now you can use strtok to tokenize your input string and then examine the tokens for your integer value integer. One of the answers here [link] suggests using strtok to tokenize a string.
If you know the format of you string or know that there will always be a single integer value then you can use string::find_first_of and string::find_last_of [link] and then just get the substring and use string::stoi.

quickly find a short string that isn't a substring in a given string

I've been trying to serialize some data with a delimiter and ran into issues.
I'd like to be able to quickly find a string that isn't a substring of given string if it contains a delimiter, so that I can use that for a delimiter.
If I didn't care about size the quickest way to find it would be to check a character in the given string, and pick a different character, make a string of the given string's length of only that character.
There may be a way to do some sort of check, testing first the middle characters, then the middle of the first and last segment... but I didn't see a clear algorithm there.
My current idea, which is fairly quick but non optimal is
initialize a hash with all characters as keys and 0 as a count
Read string characters as bytes using the hash to count.
walk the keys finding the smallest number of characters. stopping immediately if I find one that has zero characters.
Use that number of characters plus one as the delimiter.
I believe that is O(n), though obviously non the shortest. But the delimiter will always be no more than n/256 + 1 characters.
I could also try some sort of trie based construction, but I'm not quite sure how to implement that and thats 0(n^2) right?
https://cs.stackexchange.com/questions/21896/algorithm-request-shortest-non-existing-substring-over-given-alphabet
may be helpful.
Your counting of characters method isn't sufficient because you're only talking about the current string. The whole point of a delimiter is that in theory you're separating multiple strings, and therefore you'd need to count all of them.
I see two potential alternative solutions
Pick a delimiter and escape that delimiter in the strings.
Can use URI::Escape to escape a specific character, say &, and use that as the delimiter.
Specify the size of your string before you send it. That way you know exactly how many characters to pull. Essentially pack and unpack
And because I'm already on the train of alternative solutions, might as well propose all of the other serialization modules out there: Comparison of Perl serialization modules
I like the theory behind a task like this, but rings too much like an XY Problem
I agree with #Miller that your best bet is to pick a character and escape that in the text.
However, this is not what you asked, so I'll attempt to answer the question.
I take it these strings are long, so finding the delimiter is time-sensitive.
In straight Perl, the hash idea may well be as fast as you can get. As a native C extension, you can do better. I say this because my experience is that Perl array access is pretty slow for some reason, and this algorithm uses arrays to good effect:
int n_used_chars = 0;
int chars[256], loc_of_char[256];
for (int i = 0; i < 256; i++) used_chars[i] = loc_of_char[i] = i;
for (int i = 0; i < string_length; i++) {
char c = string[i];
int loc = loc_of_char[c];
if (loc >= n_used_chars) {
// Character c has not been used before. Swap it down to the used set.
chars[loc] = chars[n_used_chars];
loc_of_char[chars[loc]] = loc;
chars[n_used_chars] = c;
loc_of_chars[c] = n_used_chars++;
}
}
// At this point chars[0..n_used_chars - 1] contains all the used chars.
// and chars[n_used_chars..255] contains the unused ones!
This will be O(n) and very fast in practice.
What if all the characters are used? Then things get interesting... There are 64K two-byte combinations. We could use the trick above, and both arrays would be 64K. Initialization and memory would be expensive. Would it be worthwhile? Perhaps not.
If all characters are used, I would use a randomized approach: guess a delimiter and then scan the string to verify it's not contained.
How to make the guess in a prudent way?

Properties of a string class in C++

I am working through C++ program design by Cohoon and Davidson. This is what it says about string class attributes (3rd Edition, Page 123):
Characters that comprise the string
The number of characters in the string
My question is: If we know the characters in the string, does not it implies we already know about number of characters in the string? What is the need to explicitly specify the second attribute?
You are right but length is required in many places like counting, or knowing the length/end of malloc memory so it is better to store length as additional property to make your program run fast.
Consider what will happen if the program needs to count the chars all the way just to tell you how many are there in it. Moreover when this feature is accessed frequently.
So it simply saves time storing length too.
So all actual implementations of string classes do store length of the string.
If we know the characters in the string, does not it implies we already know about number of characters in the string?
Well in C we know the number of elements because we can count up to the NULL terminal. But think how expensive it is to get the length of a string? It takes walking the entire string. For such a common operation, why wouldn't we want this to be a constant-time operation?

Write a program to count how many times each distinct word appears in its input

This is a question(3-3) in accelerated C++.
I am new to C++. I have thought about this for a long time, however, I can't figure it out.
Will anyone resolve this problem for me?
Please explain it in detail, you know I am not very good at programming. Tell me the meaning of the variables you use.
The best data structure for this is something like a std::map<std::string,unsigned>, but you don't encounter maps until chapter 7.
Here are some hints based on the contents of chapter 3:
You can put strings in a vector, so you can have std::vector<std::string>
Strings can be compared, so std::sort works with std::vector<std::string>, and you can check if two strings are the same with s1==s2 just like for integers.
You saw in chapter 1 that std::cin >> s reads a word from std::cin into s if s is a std::string.
To provide maximal learning experience, I will not provide pastable code. That's an exercise. You have to do it yourself to learn as much as you can.
This is the perfect scenario for employing a kind of map that creates its value type upon accessing a non-existing key. Fortunately, C++ has such a map in its standard library: std::map<key_type,value_type> is exactly what you need.
So here's the jigsaw pieces:
you can read word by word from a stream into a string by using operator >>
you can store what you find in a map of words (strings) to occurrences (unsigned number type)
when you access an entry in the map through a non-existing key, the map will helpfully create a new default-constructed value under that key for you; if the value happens to be a number, default-construction will set it to 0 (zero)
Have fun put this together!
Here's my hint. std::map will be your friend.
Here is an algorthm you could use, try coding something and put you results here. People can then help you get further.
Scan down the string collecting each letter until you get to a word boundary (say space or . or , etc).
Take that word and compare it to the words you've already found, if already found then add one to the count for that word. If it's not then add that word to the list of words found with a count of 1.
Carry on down the string
Well, you need a way of getting individual words from the input stream (perhaps something like an "input stream" method applied to the "standard input stream") and a way of storing those strings and counts in some sort of "collection".
My natural homework cynicism and general apathy towards life prevent me from adding more detail at the moment :-)
The meaning of any variables I use is fairly self-evident since I tend to use things like objectsRemaining or hasBeenOpened.