Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
So I was making guessing game to learn something (I'm a beginner) and at the start I faced the problem that I didn't know how to do rng or something like that so I came up with idea where I just ask user to give his name and something he hates and I need to make this input somehow change to number (any kind except binary).
So in short I need a way to change any inputted text (string) to any integer number.
Here is an example of how to use a hash function, that already exists for the standard library.
#include <cstdio>
#include <string>
#include <iostream>
#include <functional>
int main() {
std::cout << "Starting Process!" << std::endl;
std::cout << "Enter Name: ";
std::string name;
std::cin >> name;
std::hash<std::string> hash_fn;
size_t str_hash = hash_fn(name);
std::cout << str_hash << '\n';
return 0;
}
I would suggest you to take a look at the "random" library if you want rng or to use hashing as other suggested.
If you want to generate yourself pseudo-random numbers from an input string, you could do the following:
To acces a character, you could use the [ ] operator, something like that:
std::string str = "The Name";
str[index]; // to acces a character
Cast the characters into integers to work with them. Keep in mind that every character has an ASCII value, so you could do something like this:
static_cast<int>(str[2]);
Now you have accesed the third character, according to the string above, 'e'. Which happens to be 101 when transformed into an int (remember, the ASCII value).
You can then create some algorithm using that.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to randomly display a user input string using c++ but I couldn't find a way to do.
Currently I am pre defining some strings
#include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
const string wordlist[4] = {"hi","hello","what's up","wassup"};
string word = wordlist [rand()%4];
cout<<word;
return 0;
}
What I want is:- I don't want to pre define them. I want the user to type in 4 words and I will display a word from the 4 words given by the user (randomly).
To do that you will have to first remove const qualifier from wordlist array.
srand(time(0));
std::vector<string> wordlist(4);
for(auto& s: wordlist) std::cin>>s;
string word = wordlist [rand()%4];
cout<<word;
Line 3 is C++11's range based for loop, this way I can easily loop over elements of std::vector<string> without indices.
If there are multiple words in a string then use getline(cin,s) accordingly. Then input each string in a new line. But be careful when mixing cin and getline for taking input.
You can use std::array if the size is going to be fixed (i.e. 4) as mentioned in comments.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am doing a Date class which takes a string as a parameter that is like :
11/13/2007
9/23/2008
9/23/2008
... and set it month, date and year objects, How can I use the substr() function, or are there any other functions ?
In your case, I would use the good old C(!) sscanf function:
unsigned int year, month, day;
char c;
if(sscanf(input, "%u/%u/%u%c", &month, &day, &year, &c) == 3)
{
// check ranges of your date variables!
}
You seem to use American date format, so I set the parameters accordingly.
Wondering why I'm reading an additional character ? It catches additional data at the end of your date string to detect invalid formats (if data follows, result will be 4, otherwise, only 3 values are read, which will be returned). One drawback: before the three numbers, white space is ignored, so if you wanted to disallow, you would need additional checks (e. g. "%n %n%u" and comparing, if the two corresponding values are equal).
See sscanf documentation (scanf for parameters).
(If your input is a ::std::string instance, you need to use sscanf(input.c_str(), ...), of course.)
If you are using C++11 you can use <regex> library:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string date = "1/1/1970";
std::regex dateRegex("(\\d\\d?)/(\\d\\d?)/(\\d{4})");
std::smatch match;
if (regex_match(date, match, dateRegex)) {
std::cout << match.str(1) << std::endl;
std::cout << match.str(2) << std::endl;
std::cout << match.str(3) << std::endl;
}
else {
// error
}
return 0;
}
This is maybe an overkill for your situation but remember that by using regular expression you are also doing some form of validation on your input. In above example, if you pass anything that doesn't have the form dd/dd/dddd where "d" is a digit you will enter the "error" block of code. Of course, 99/99/9999 will count as a valid input but you can also solve that case with more complicated regex.
Another option for parsing strings with delimiter is using getline function.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I can't seem to come up with a chunk of code that traps the user until it gets a positive int and prompts the user appropriately if the user accidentally types a character or random garbage like "-1-3-4-39-32xfi3/". I just need a neat failproof cin loop structure and can't figure it out. Thanks.
I'm just wondering what other people do regarding console input to make draw ideas from that..how you get around bad input.
Do this:
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
for (std::string line; std::getline(std::cin, line); )
{
std::istringstream iss(line);
unsigned int n;
if (!(iss >> n >> std::ws) || iss.get() != EOF)
{
std::cout << "Bad input ('" << line << "'), ignoring.\n";
continue;
}
std::cout << "Success! We read: " << n << "\n";
return EXIT_SUCCESS;
}
std::cout << "Premature end of input!\n";
return EXIT_FAILURE;
}
In other words, continue reading input from the user until you are able to parse the input as the kind of data you want. I chose line-based processing, which is often the most natural, but any notion of "record" that you can skip if it isn't right will do. Note that it's possible the program never succeeds, namely if the user refuses to provide any good input.
I typically read an entire line with std::getline, then attempt to convert it to an integer with strtol. If the result is less than 0, they typed a leading -. strtol returns a pointer to the first character of input that couldn't be converted as an integer, so if it points to anything but \0, you know the user typed in something that couldn't be converted.
I really should switch to using std::stoi instead of strtol though. It supports pretty much the same capabilities, but its input is a std::string instead of a C-style string like strtol uses. I only continue to use strtol out of long habit, not because it's really a better solution.
Depending on what you have available, and how you want to respond to bad input, another possibility to consider would be boost lexical_cast. This throws an exception if it can't convert the entire input to the target type, so if you want an exception it may be more convenient (but if you don't want exceptions, it'll probably just cause you extra work).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
So I have a file with like 5-6 lines of text, and I need to find which one has the most words and output it into another file. Any of you have suggestions?
I'm not that advanced in C++, I' using classes, arrays, no vectors or such.
Other code is rather irrelevant in my program, but if you need it i'll paste it here.
EDIT: http://pastebin.com/zh7HPCtT here's my code, the first part of it finds how many words in a line are longer than the first word.
I haven't added anything else for the other half of the assignment.
Try this:
read each line
count the words in it
if it has more words than any other line you've seen, save it
after the file is exhausted, print the saved line
One of the simplest solutions is to use a string max that you will use in your loop.
Then you loop over all lines in your file, and for each line line you compare the number of words in line against the number of words in max, and if line has more words, assign it to max.
After you have done that for all lines, open a file or just dump to standard output (enabling your user to redirect your output to some file itself), and print max.
The core algorithm is very much like finding the maximum of two numbers, and in fact you can just use std::max from the standard library, with your own comparator.
Just for fun, here's a very suboptimal solution:
#include <algorithm>
#include <sstream>
#include <string>
#include <iostream>
std::string longest_phrase (std::istream &is) {
std::string longest, current_line;
while (getline(is, current_line))
longest = max(longest, current_line, [] (std::string const &lhs, std::string const &rhs) {
std::stringstream lhss(lhs), rhss(rhs);
std::string sink;
int words_lhs = 0, words_rhs = 0;
while (lhss >> sink) ++words_lhs;
while (rhss >> sink) ++words_rhs;
return words_lhs < words_rhs;
});
return longest;
}
std::string longest_phrase (std::string const &content) {
std::istringstream ss(content);
return longest_phrase(ss);
}
int main () {
std::cout << longest_phrase("Hello, I am a cat!\n"
"Hello, I am an unhappy bear!\n"
"Pardon?!\n"
"WtfOMG!?=§\"$%&/!!?µ€#+%$§==!!!") << '\n';
}
It will output Hello, I am an unhappy bear!\n. There's a lot of resource waste and you should make it more stateful, but it will serve you as a starting point.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am trying to display image from different locations. There are car, airplane, chair etc. files need to be display. I put those words (car, airplane) in a text file. I can read words but when I put them in sprintf, I get nonsense characters.
I can display the words with cout<<*j<<endl;. But cout<<filename<<endl; gives me weird result.
string words;
std::vector<string>list;
fstream file;
file.open("h.txt");
while(!file.eof())
{
file >> words;
list.push_back(words);
}
for(vector<string>::iterator j=list.begin(); j!=list.end(); j++)
{
cout<<*j<<endl;
for(i=1; i<5; i++)
{
sprintf( filename,"D:\\101_ObjectCategories\\%s\\image_%04d.jpg",*j,i);
cout<<filename<<endl;
The C function sprintf() is oblivious of the C++ classes. If you really want to print a std::string using sprintf() you'll need to extract a C string:
sprintf(filename, "D:\\101_ObjectCategories\\%s\\image_%04d.jpg", j->c_str(), i);
You should also use snprintf() together with the size of the buffer you pass as filename to prevent overflow. Personally, I wouldn't really bother and rather using std::ostringstream in the first place:
std::ostringstream out;
out << "D:\\101_ObjectCategories\\" << *j << "\\image_"
<< std::setfill('0') << std::setw(4) << i << ".jpg";
std::string filename = out.str();
(after including <sstream> and <iomanip>).
Use must use *j.c_str():
sprintf( filename,"D:\\101_ObjectCategories\\%s\\image_%04d.jpg",*j.c_str(),i);
Otherwise, the string class itself is cast into a char* explicitly which is garbage of course :)