Compare an input array with string - c++

How can use the proper code to compare an input array with string?
#include<iostream>
#include<cstring>
#include<stdlib.h>
using namespace std;
int main()
{
char user[30] ;
string nama[5]="ali33,abu123,ahmad456,kasim123,rahmat123";
int w,i ;
cout<<"username : ";
cin>>user[30];
for(i=0;i>=0;++i)
{
w=strcmp(nama[i],user);
}
I'm using Dev-C++, and the error is on this line:
w=strcmp(nama[i],user)
Does anyone know how to fix this?

I suggest you study this:
std::vector<string> nama = { "ali33", "abu123", "ahmad456",
"kasim123", "rahmat123" };
string user;
cout << "username : ";
int w = -1;
if (cin >> user)
{
for(int i = 0; i < nama.size(); ++i)
if (nama[i] == user)
w = i;
if (w != -1)
std::cout << user << " found at [" << w << "]\n";
else
std::cout << user " not found\n";
}
Notes: use std::vector not arrays until you understand the differences, and std::string for any text. You could use the C++ Standard Library function std::find() to see if the user value appears in nama, but it's good to learn how to write a loop and do things yourself too.

`strcmp()`**is used when comparing c-string data types. Convert your char data type to string and use compare function as illustrated below**`
int main()
{
char user[30];
string nama[5] = { "ali33","abu123","ahmad456","kasim123","rahmat123" };
int w = -99;
int i;
cout << "username : ";
cin >> user[30];
string temp(user);
for (i = 0; i < 5; i++)
{
w = nama[i].compare(temp);
}
}

Related

When I input a number in char type, why i can't get a whole number?

I input a number in char type variable. like 12 or 22. but, console show me a 1 or 2.
How i get a whole number 12 ,22 in console?
#include <iostream>
int main()
{
using namespace std;
char a = 0;
cin >> a;
cout << a << endl;
return 0;
}
Here is console result.
12
1
C:\Users\kdwyh\source\repos\MyFirstProject\Debug\MyFirstProject.exe(프로세스 18464개)이(가) 종료되었습니다(코드: 0개).
이 창을 닫으려면 아무 키나 누르세요...
The reason I don't use int, string and something is because I want to get both number and Character in one variable.
So I want to see the results of combined numbers and character at the same time.
in that process i can't get a whole number.
#include <iostream>
using namespace std;
int index = 0;
constexpr int pagenum = 10;
void chapterlist(void);
void nextlist(void);
void beforelist(void);
void movechapter(char a);
int main(void)
{
char userin = 0;
bool toggle = 0;
cout << "결과를 볼 챕터를 고르시오." << endl;
chapterlist();
cout << "다음 페이지로 이동: n" << endl;
cin >> userin;
if (userin == 'n')
{
backflash:
while(toggle == 0)
{
nextlist();
cin >> userin;
if (userin == 'b')
{
toggle = 1;
goto backflash;
}
else if (userin == 'n')
continue;
else
{
system("cls");
movechapter(userin);
break;
}
}
while(toggle == 1)
{
beforelist();
cin >> userin;
if (userin == 'n')
{
toggle = 0;
goto backflash;
}
else if (userin == 'b')
continue;
else
{
system("cls");
movechapter(userin);
break;
}
}
}
else
{
system("cls");
movechapter(userin);
}
return 0;
}
void chapterlist(void)
{
int x = 0;
for (x = index + 1; x <= index + 10; x++)
cout << "Chapter." << x << endl;
}
void nextlist(void)
{
system("cls");
cout << "결과를 볼 챕터를 고르시오." << endl;
index = index + pagenum;
chapterlist();
cout << "다음 페이지로 이동: n" << endl;
cout << "이전 페이지로 이동: b" << endl;
}
void beforelist(void)
{
system("cls");
cout << "결과를 볼 챕터를 고르시오." << endl;
index = index - pagenum;
chapterlist();
cout << "다음 페이지로 이동: n" << endl;
cout << "이전 페이지로 이동: b" << endl;
}
void movechapter(char a)
{
cout << "선택한 Chapter." << a << "의 결과입니다." << endl;
}
In movechapter(), console show me a is 1 or 2, not 12, 22.
First, you have to understand what achar type is.
Character types: They can represent a single character, such as 'A' or '$'. The most basic type is char, which is a one-byte character. Other types are also provided for wider characters.
To simplify that, char can only hold one character.
Where as with your code, "12" is actually 2 separate characters, '1' and '2', and that's the reason it would not work.
Instead of declaring a as a char type, you could declare it as an int type, which is a type designed to hold numbers. So you would have:
int a = 0;
However, do note that int often has a maximum value of 2^31.
Or you could use std::string to store character strings. However, do note that if you wish to do any calculations to your string type, you would need to convert them to a number type first:
int myInt = std::stoi(myString);
Edit:
So I have re-checked your code after your update, there is nothing wrong with using std::string in your case. You can still check if user have input n or b by:
if (userin == "n")
Note that you would use double quotation mark, or "letter", around the content that you want to check.
On the other hand, you could use:
if(std::all_of(userin .begin(), userin.end(), ::isdigit))
To check if user have input a number.
Although char is just a number, it's presumed to mean "single character" here for input. Fix this by asking for something else:
int a = 0;
You can always cast that to char as necessary, testing, of course, for overflow.
You should be reading characters into a string, and then converting that string into an int. It would also probably make more sense to use something like getline() to read input, rather than cin >> a.
#include <string>
#include <iostream>
#include <stdexcept>
#include <stdio.h>
int main() {
std::string input_string;
/* note that there is no function that will convert an int string
to a char, only to an int. You can cast this to a char if needed,
or bounds check like I do */
int value;
while(1) {
getline(std::cin, input_string);
/* std::stoi throws std::invalid_argument when given a string
that doesn't start with a number */
try {
value = std::stoi(input_string);
} catch (std::invalid_argument) {
printf("Invalid number!\n");
continue;
}
/* You wanted a char, the max value of a `char` is 255. If
you are happy for any value, this check can be removed */
if (value > 255) {
printf("Too big, input a number between 0-255\n");
continue;
}
break;
}
printf("Number is %hhu\n", value);
}

An extra character appears while converting a char array to string in C++

So I have written a code where I take three strings at each iteration and store all the combinations of length three(maintaining the order) taking each character from those three strings. I use a char array to make those combinations and then I convert that char array to a string and insert in an unordered_set. While doing so, I encountered a problem where I see an extra character being added at the end of some strings.
Here is my code:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
char charArr[3];
string strArr[3];
unordered_set<string> aSet;
cin >> n;
while(n-- > 0) {
cin >> strArr[0] >> strArr[1] >> strArr[2];
for(int x=0; x<strArr[0].size(); x++) {
charArr[0]=strArr[0][x];
for(int y=0; y<strArr[1].size(); y++) {
charArr[1]=strArr[1][y];
for(int z=0; z<strArr[2].size(); z++) {
charArr[2]=strArr[2][z];
string tempStr(charArr);
cout << "Len = " << tempStr.length() << "\n";
aSet.insert(tempStr);
}
}
}
}
cout << "Check aaz = " << aSet.count("aaz") << "\n";
for(auto it=aSet.begin(); it!=aSet.end(); it++) {
cout << *it << "\n";
}
}
Here is a sample input:
2
a a z
c a c
Here is the output:
Len = 4
Len = 3
Check aaz = 0
cac
aaz
Here is a picture of how it looks in my pc:
However when I ran the same code for same input in ideone, it gave me the correct answer. Which is as follows:
Len = 3
Len = 3
Check aaz = 1
cac
aaz
Can anybody please explain what's going on here?
N.B: I'm using CodeBlocks and C++14

C++ Replacing a character in an array without the use of C-String Library Functions

I was given a set of questions, basically asking me to recreate the utility of certain library functions such as strlen() and strcpy() without using them.
However, one of the questions has gotten me stumped. It's a function that replaces a character in a string with anything you choose.
Example :
Str : marix xdyssey
target : x
replacement : o
Output : mario odyssey
This is what I have right now
#include <iostream>
using namespace std;
int replace(char *s2, char target, char replacementChar);
const int MAX_SIZE = 128;
int main()
{
char str2[MAX_SIZE], target, replacement;
int change;
cout << "Enter your string : " << endl;
cin.getline(str2, MAX_SIZE);
cout << "What's your target?" << endl;
cin >> target;
cout << "What do you want to replace it with?" << endl;
cin >> replacement;
replace(str2, target, replacement);
}
int replace(char *s2, char target, char replacementChar)
{
int change = 0;
for(int i=0; s2[i]!='\0'; i++)
{
if(s2[i] == target)
{
swap(s2[i], replacementChar);
change++;
}
}
cout << "There were " << change << " change(s)." << endl;
cout << s2;
return change;
}
And even though "change" returned 2, I was given the output of "mario xdyssey".
Any advice or hints as to how to proceed would be greatly appreciated.
Change
swap(s2[i], replacementChar);
to:
s2[i] = replacementChar;
swap() exchanges the values of the two variables, so after the first replacement, replacementChar contains the same thing as target, so nothing gets updated.

How do I use cin to get a string instead of hard-coding it?

As a homework exercise we were asked to use strchr to count the amount of times a single letter appears in a string of text. It needs to count upper or lower cases as equal. It was suggested we use some sort of bit operations.
I managed to get a working program.
But i would like to make the program more interactive by allowing me to use a cin to input the string instead of typing the string directly into the source code (Which was asked by the exercise).
Is it possible to do this? Or is it not possible in the way i wrote this code.
#include <iostream>
#include <cstring>
using namespace std;
int main(){
const char *C = "This is a necesarry test, needed for testing.";
char target = 'A';
const char *result = C;
const char *result2;
int count = 0;
int j[26] ={0};
//================================================================================================================================================
for(int i = 0; i <= 51; i++){
if (i == 26){
target = target + 6;
}
result2 = strchr(result, target);
while(result2 != NULL){
if (result2 != NULL){
result2 = strchr(result2+1, target);
if (i <= 25){
j[i] = j[i] +1;
}
if(i > 25){
j[i-26] = j[i-26] +1;
}
cout << target << "\t";
}
}
cout << target << endl;
target++;
}
char top = 'a';
for(int o = 0; o<= 25; o++){
cout << "________________________________\n";
cout << "|\t" << top << "\t|\t" << j[o] << "\t|" << endl;
top++;
}
cout << "________________________________\n";
}
Simply use getline() to get a string of characters from the console. Using getline you can also consider the spaces in the user input.
string input;
getline(cin, input);
Now to use this with the strchr functionn you simply have to convert this into a C Type string which can be done as follows :
input.c_str
This returns a C type string so you can put this as an arguement to the function,
You will need
#include <string>

Algorithm to print the reversed number given by user?

I've written a small program in C++ that prompts the user for input, the user gives a number, then the computer displays the number reversed.
For example: 17 becomes 71. 123 becomes 321.
This is the program:
#include <iostream>
#include <string> //for later use.
using namespace std;
int rev(int x)
{
int r = 0;
while(x)
{
r = (r*10) + (x%10);
x = x/10;
}
return r;
}
int main()
{
int nr;
cout << "Give a number: ";
cin >> nr;
rev(nr);
cout << nr;
return 0;
}
The final result of the program: prints the same number, function has no effect. What am I doing wrong? I tried several solutions but to no avail.
You need to change rev(nr); to nr = rev(nr);
or alternately change your function to:
void rev(int& x)
{
int r = 0;
while(x)
{
r = (r*10) + (x%10);
x = x/10;
}
x = r;
}
You're doing it right, but you're not grabbing your return value (the reversed value).
To solve this, just assign or print the return value:
cout << rev(nr);
or
nr = rev(nr);
cout << nr;
While probably not in the intended spirit, the simple answer is that if you're only going to display it in reverse, you can cheat and just work with a string:
std::string input;
std::cin >> input;
std::cout << std::string(input.rbegin(), input.rend());
You're not actually using the value that rev returns. You're just using the value nr which you pass to rev, and since you don't pass by reference, rev isn't being affected locally.
What you want to say is:
int nr;
cout << "Give a number: ";
cin >> nr;
int result = rev(nr);
cout << result;
return 0;
There is a std::reverse function in the STL, which works with collections.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
long int i = 0;
do {
std::cout << "Gimme a number: " << std::endl;
} while (not (std::cin >> i)); // make sure it *is* a number
std::string display = std::to_string(i); // C++11
std::reverse(display.begin(), display.end());
std::cout << display << "\n";
}