C++ Finding a string's nth character - c++

I am trying to do my assignment for CS, but I can not find how to get a string's first character.
Example input : 5ABCD1AB1AD
Desired output: 5
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string word;
word = argv[1];
cout << "Word: " << word << "\n";
int length = word[0];
cout << "Word's length : " << length << "\n";
for(int i = 1; i < argc; i++){
for(int j = 0; j < length; j++){
cout << argv[i][j] << "\n";
}
}
}

word[0] is a character. There is a difference between the character '5' and the number 5. If you assign a character to an int you will get the encoding value for that character.
To convert a character to its numeric value you can subtract '0', since the encoding values for the digits are consecutive.
int length = word[0] - '0';

Related

Why isn't it initializing it with all zeros as a static integers array?

Why does the two arrays act differently in this case?
#include <bits/stdc++.h>
using namespace std;
int main() {
char a[100] = {}; // all white spaces
int b[100] = {} ; // all 0
for(int i = 0; i < 100; i++)
cout << a[i] << "\n";
for(int i = 0; i < 100; i++)
cout << b[i] << "\n";
}
It is indeed initialized to zeroes. Since it's a character array, zeros are just the \0 character. Change that line from
cout << a[i] << "\n";
to
std::cout << '[' <<a[i] <<']' <<std::boolalpha<< (a[i] == '\0') << "\n";
help confirm what you expect is true.
char a[100] = {}; // all white spaces
This line will initiate all elements to integer value 0, which when converted to it's ASCII equivalent is a null character.

C++ Letter Occurrences

Write a C++ program that reads input from a text file and counts the number of characters read from the input. If the character read is a letter ('a'-'z'), counts the number of times that letter occurs [using an array] (both uppercase and lowercase should be counted as the same letter) in the input. Output the percentage of each letter in the input text, as well as the percentage of non-letter characters in the input.
Yes, this is a homework question, and I have most of it, but for some reason it isn't adding like I'd hoped.
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
// make array with size of 26
// make array with all letter of alphabet
const int size = 26;
int narray[size];
char larray[26] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
// all variables
int count = 0;
char character;
int length = 0;
int amount = 0;
int sum = 0;
double percent = 0;
// open file user inputs
ifstream input;
string file;
cout << "Please enter the file to be read" << endl;
cin >> file;
input.open(file);
if (input.fail())
{
cout << "Can't open file successfully." << endl;
return 1;
}
// count amount of characters and spaces in while loop
while (!input.eof()) //loop until the file ends
{
getline(input, file); // read every character
int c = file.length(); // count length
length += c;
}
// make every variable in array equal to 0
for (count = 0; count < size; count++)
{
narray[count] = amount;
}
// make for loop to read every character
for (int i = 0; i < length; i++)
{
input.get(character); // read characters
if (character <= 'A' && character >= 'z')
{
narray[tolower(character)-'a']++; // find out which variable of the array it is and add 1 to the amount
sum++;
}
}
// make for loop to print out array percentages
for (int j = 0; j < size; j++)
{
percent = (narray[j] / length) * 100;
cout << larray[j] << " " << percent << "%" << endl;
}
int non = (((length - sum) / length) * 100);
cout << "Non letter characters " << non << "%" << endl;
input.close();
return 0;
}
Your code is a little more complicated than it needs to be, but worse it has several bugs in it.
You are using 2 separate loops to do the job that 1 loop can do.
You are calling input.eof() before you have performed a read operation. The stream's state is not updated until after a read is attempted, so calling eof() before the 1st read is undefined behavior.
After you have read through the stream one time to EOF just to count its characters, you are not seeking the stream back to the beginning so you can then read the characters all over again.
You are not counting line break characters in the 1st loop, but you are reading line break characters in the 2nd loop, so the 2nd loop (potentially) won't read as many characters as the 1st loop had counted.
You are not testing for Uppercase and Lowercase letters correctly, and you are not accounting for the fact that in ASCII, there are 6 non-letter characters between the set of Uppercase letters and set of Lowercase letters. Your indexing of the narray[] array is all wrong while you are counting characters.
You are not accounting for the possibility that the file might be completely empty, or have ONLY linebreak characters in it and no non-linebreak characters. If either of those condition happens, your length variable will be 0, and you would get errors when you calculate percentages when dividing by 0.
With that said, try something more like this instead:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// make array with size of 26
const int size = 26;
int narray[size] = {}; // make every variable in array equal to 0
// all variables
char character;
int count = 0;
int sum_letters = 0;
int sum_non = 0;
double percent;
string file, line;
// prompt user for filename
cout << "Please enter the file to be read" << endl;
getline(cin, file);
// open file
ifstream input(file);
if (!input.is_open())
{
cout << "Can't open file." << endl;
return 1;
}
//loop until the file ends
while (getline(input, line))
{
count += line.size(); // count every character
for (int j = 0; j < line.size(); ++j)
{
character = line[j];
// find out which variable of the array it is and add 1 to the amount
if (character >= 'A' && character <= 'Z')
{
narray[character-'A']++;
++sum_letters;
}
else if (character >= 'a' && character <= 'z')
{
narray[character-'a']++;
++sum_letters;
}
else
++sum_non;
}
}
input.close();
if (count != 0)
{
// make for loop to print out array percentages
for (int j = 0; j < size; ++j)
{
percent = (double(narray[j]) / count) * 100.0;
cout << ('a'+j) << " " << percent << "%" << endl;
}
percent = (double(sum_non) / count) * 100.0;
cout << "Non letter characters " << percent << "%" << endl;
}
else
{
cout << "File has no characters" << endl;
}
return 0;
}
If you want to include line breaks in the percentage of non-letter characters, then use this instead:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// make array with size of 26
const int size = 26;
int narray[size] = {}; // make every variable in array equal to 0
// all variables
char character;
int count = 0;
int sum_letters = 0;
int sum_non = 0;
double percent;
string file, line;
// prompt user for filename
cout << "Please enter the file to be read" << endl;
getline(cin, file);
// open file
ifstream input(file);
if (!input.is_open())
{
cout << "Can't open file." << endl;
return 1;
}
//loop until the file ends
while (input.get(character))
{
++count; // count every character
// find out which variable of the array it is and add 1 to the amount
if (character >= 'A' && character <= 'Z')
{
narray[character-'A']++;
++sum_letters;
}
else if (character >= 'a' && character <= 'z')
{
narray[character-'a']++;
++sum_letters;
}
else
++sum_non;
}
input.close();
if (count != 0)
{
// make for loop to print out array percentages
for (int j = 0; j < size; ++j)
{
percent = (double(narray[j]) / count) * 100.0;
cout << ('a'+j) << " " << percent << "%" << endl;
}
percent = (double(sum_non) / count) * 100.0;
cout << "Non letter characters " << percent << "%" << endl;
}
else
{
cout << "File is empty" << endl;
}
return 0;
}

Display duplicate characters in a string

I wrote some code in C++ to display duplicate characters in a string, but if a character is repeated more than three times, the code prints the repeated character more than once.
For example if the string is aaaddbss, it should only print out ads but it prints aaads instead.
What am I doing wrong?
cout << " Please enter a string" << endl;
cin.getline(input, 100); // example input (ahmad wahidy) the output reads a a h a d instead of a h d
for (int i = 0;input[i]!='\0'; i++)
{
for (int j = i+1;input[j]!='\0'; j++)
{
if (input[i] == input[j])
{
cout << input[i] << " ";
}
}
}
cout << endl;
Instead of using your own custom methods, why not use a short and standard method?
Given an std::string input with the text, this will print the unique chars:
std::set<char> unique(input.begin(), input.end());
for (auto & c : unique)
{
std::cout << c << " ";
}
std::cout << std::endl;
You can use std::count and std::set:
#include <string>
#include <set>
#include <iostream>
using namespace std;
int main()
{
string s = "hellohowareyou";
set<char>the_set(s.begin(), s.end());
for (char i:the_set)
if (count(s.begin(), s.end(), i) > 1)
cout << i << endl;
}
Output:
e
h
l
o
If you are not allowed to use a map (and probably also not allowed to use a set), you could simply use an array of integers to count occurrences, with one entry for each possible char value. Note that a character - when taken as an ASCII value - can be directly used as an index for an array; however, to avoid negative indices, each character value should first be converted to an unsigned value.
#include <iostream>
#include <limits>
int main() {
const char* input = "aaaddbss";
int occurrences[UCHAR_MAX+1] = { 0 };
for (int i = 0;input[i] !='\0'; i++)
{
unsigned char c = input[i];
if (occurrences[c]==0) {
occurrences[c]++;
}
else if (occurrences[c]==1) {
occurrences[c]++;
cout << "duplicate: " << c << endl;
}
}cout << endl;
}

Count the same numbers in a string and print them out as stars c++

I am writing a program which has a string, and then I read through the string and put all the digits in a array using vector and then using count I have to count the same numbers in that array and after that print the number as stars.
Error I am getting is invalid operands to binary expression.
Here is the code.
#include <iostream>
#include <vector>
#include <algorithm>
#include<array>
using namespace std;
int main() {
vector<string> array;
string grades = "01211342111153332211111232454444";
int newarray[31];
for(int i = 0 ; i < grades.length(); i++){
array.push_back(grades.substr(i,1));
}
int zero = count(std::begin(array),std::end(array),0);
int one = count(std::begin(array),std::end(array),1);
int two = count(std::begin(array),std::end(array),2);
int three = count(std::begin(array),std::end(array),3);
int four = count(std::begin(array),std::end(array),4);
int five = count(std::begin(array),std::end(array),5);
// also used this way int zero = count(array.begin(),array.end(),0); but still getting error.
for(int i = 0 ; i < one ; i ++){
cout << '1 - ' << '*' << ' ';
}
for(int j = 0 ; j < two ; j++){
cout << '2 - ' << '*' << ' ';
}
}
Learning C++ so hopefully people go a bit easy on me.
Many issues here.
First, you are comparing number to strings in int zero = count(std::begin(array),std::end(array),0);. You want to compare string to string.
Second, you are trying to cout '1 - '. ' is for characters, so you should use " instead.
Finally, in the cout, you need to loop only on the stars and the space, not the "1 - ". And flush the whole thing to print on your console, with either cout<<"\n"; or cout<<std::endl;.
You can try the following:
int main()
{
vector<string> array;
string grades = "01211342111153332211111232454444";
int newarray[31];
for(int i = 0 ; i < grades.length(); i++){
array.push_back(grades.substr(i,1));
}
int zero = count(std::begin(array),std::end(array),"0");
int one = count(std::begin(array),std::end(array),"1");
int two = count(std::begin(array),std::end(array),"2");
int three = count(std::begin(array),std::end(array),"3");
int four = count(std::begin(array),std::end(array),"4");
int five = count(std::begin(array),std::end(array),"5");
cout << "1 - ";
for(int i = 0 ; i < one ; i ++){
cout << '*' << ' ';
}
cout << "\n";
cout << "2 - ";
for(int i = 0 ; i < two ; i ++){
cout << '*' << ' ';
}
cout << "\n";
/*....*/
}

Count number of occurrences in string c++?

I'm used to java, and struggle with basic syntax of C++ despite knowing theory. I have a function that is trying to count the number of occurrences in a string, but the output is a tab bit weird.
Here is my code:
#include <cstdlib>
#include <iostream>
#include <cstring>
/*
main
* Start
* prompt user to enter string
* call function
* stop
*
* count
* start
* loop chars
* count charts
* print result
* stop
*/
using namespace std;
void count(const char s[], int counts[]);
int main(int argc, char** argv) {
int counts[26];
char s[80];
//Enter a string of characters
cout << "Enter a string: "; // i.e. any phrase
cin.getline(s,80);
cout << "You entered " << s << endl;
count(s,counts);
//display the results
for (int i = 0; i < 26; i++)
if (counts[i] > 0)
cout << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
return 0;
}
void count(const char s[], int counts[]){
for (int i = 0; i < strlen(s); i++)
{
char c = tolower(s[i]);
if (isalpha(c))
counts[c - 'a']++;
}
}
Here is the output:
Enter a string: Dylan
You entered Dylan
b: 1Times
c: 1Times
d: 2Times
f: 1Times
h: 1Times
i: 1229148993Times
j: 73Times
l: 2Times
n: 2Times
p: 1Times
r: 1Times
v: 1Times
Any help you can give me would be greatly appreciated. Even though this is simple stuff, I'm a java sucker. -_-
Your counts is uninitialized. You need to first set all of the elements to 0.
You need to zeros the counts vector.
Try
counts[26]={0};
I don't know about java, but you have to initialize your variables in C/C++. Here is your code working:
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
void count(const char s[], int counts[]){
for (int i = 0; i < strlen(s); i++)
{
char c = tolower(s[i]);
if (isalpha(c))
counts[c - 'a']++;
}
}
int main(int argc, char** argv) {
int counts[26];
char s[80];
//Enter a string of characters
cout << "Enter a string: "; // i.e. any phrase
cin.getline(s,80);
for(int i=0; i<26; i++)
counts[i]=0;
cout << "You entered " << s << endl;
count(s,counts);
//display the results
for (int i = 0; i < 26; i++)
if (counts[i] > 0)
cout << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
return 0;
}