It's my first question in stack overflow so if there is some mistakes sorry about that. I'm trying to fill a 2d char array and then access each letter. I complied my code, there is no error but when I try to run it doesn't work. Here it's my code.
#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
int main() {
char ch[] = "Welcome text in a separate line.";
char strWords[5][7];
int counter = 0;
int a = 0;
for (int i = 0; i < sizeof(ch); i++) {
if (ch[i] == ' ') {
strWords[counter][a] = '\0';
counter++;
a = 0;
}
else
{
strWords[counter][a] += ch[i];
a++;
}
}
for (int i = 0; i <= 5; i++) {
for (int a = 0; a <= 7; a++) {
cout << strWords[i][a] << " ";
}
}
return 0;
}
A few things wrong with your code
int main() {
char ch[] = "Welcome text in a separate line.";
// char strWords[5][7]; <<<=== i would change to be larger that you need, just in case
char strWords[20][20];
int counter = 0;
int a = 0;
for (int i = 0; i < strlen(ch); i++) { // sizeof is wrong, you need strlen
if (ch[i] == ' ') {
strWords[counter][a] = '\0';
counter++;
a = 0;
}
else
{
//strWords[counter][a] += ch[i];
strWords[counter][a] = ch[i]; // you do not need to try to concatenate, you are already walking down the buffer with 'a'
a++;
}
}
for (int i = 0; i < counter; i++) { // use 'counter' as it has the number of lines
// since you 0 terminated the string you do not need to walk character by character
cout << strWords[i] << " ";
}
return 0;
}
You are also not detecting and terminating the last word (since there is no space after it). I will leave that to you. The code I show does not print the word 'line.'
You should really have tests to make sure you do not overflow the length or number of words.
Plus you should ideally use std::string and std::vector
Note - if, for experimentation, you do want to walk through char by char to output the strings you should look for the terminating '0' character and exit the inner loop
Related
I can't figure it out. What is wrong with my code? I am new to programming.
Program required output: Write a C++ program to find the maximum-occurring character in an array, using a loop.
My code:
#include <string.h>
using namespace std;
void FindMaxChar(char Word[])
{
int count = 0;
int max = 0;
char index = 0;
int length = strlen(Word);
for (int i = 0; i < length; i++)
{
index = Word[i];
for (int j = 0; j < length; j++)
{
if (index == Word[j])
{
count++;
}
}
if (count > max)
{
max = count;
index = Word[i];
}
}
cout << index << " is repeating " << max << " times.";
}
int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.get(Word,100);
FindMaxChar(Word);
}
My Output:
Enter the Word = caaar
r is repeating 11 times.
You never reset count each loop. So you continue incrementing it but never clear it.
Add count = 0 to the beginning of the outer for loop:
for (int i = 0; i < length; i++)
{
count = 0; // Reset counter
You're also trying to use index for two different purposes. You're both using it to store the current character you're looking at (not an index, kind of confusing that you named it like that), AND the character you've seen the most (still not an index, also confusing).
Instead, you need another variable here.
Also note that if you declare Word as char Word[100], it can only hold a c-string of length 99 (to leave room for the null character). So your cin should actually be:
cin.get(Word, 99);
Thanks to the great people of this community.
I am able to find my error and corrected it.
Correct Code :
#include <iostream>
#include <string.h>
using namespace std;
void FindMaxChar(char Word[])
{
int count = 0;
int max = 0;
char index = 0;
char final = 0;
int length = strlen(Word);
for (int i = 0; i < length; i++)
{
index = Word[i];
count = 0;
for (int j = 0; j < length; j++)
{
if (index == Word[j])
{
count++;
}
}
if (count > max)
{
max = count;
final = index;
}
}
cout << final << " is repeating " << max << " times.";
}
int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.get(Word,99);
FindMaxChar(Word);
}
Does anyone know how to write a function that counts length of an array given like in example ?
cout << length(argv[1]) << endl;
I've tried somethig like this but it says that there can't be function lentgh then.
for(int i = 0; myStrChar[i] != '\0'; i++)
{
count++;
}
EDIT1: Here is the rest of code :
#include <iostream>
#include<cstring>
using namespace std;
int i;
int length()
{
for(int i = 0; myStrChar[i] != '\0'; i++)
{
count++;
}
}
int main()
{
cout << "Hello world!" << endl;
cout << "length of first text: ";
cout << length(argv[1]) << endl;
char tab[255] = {"Ana has a cat"};
EDIT2: Now I did something like this but it puts out 108 as length of text
char argv[]="ana has a cat";
int length(char l)
{
int cou= 0;
for(int i = 0; i!=0; i++)
{
cou++;
return cou;
}
}
Hmm, what's wrong? It is a valid code - just wrap it into a function:
size_t length(const char* myStrChar)
{
size_t count = 0;
for(int i = 0; myStrChar[i] != '\0'; i++) {
count++;
}
return count;
}
You can do it a bit shorter:
size_t length(const char* myStrChar)
{
size_t count = 0;
for (; myStrChar[count] != 0; count++)
/* Do nothing */;
return count;
}
UPD:
Here is a code from the question and my comments to author:
// You're passing just a single character to this function - not array
// of char's - not a string.
// Pass char* or better const char*.
int length(char l)
{
int cou= 0;
// Ok, this loop does nothing - it's going to stop at the
// first condition check, because you assign 0 to i
// and immediately check if it is not zero - this check will
// return false and the loop will never start.
// Check the current symbol in string if it is not zero
for(int i = 0; i!=0; i++)
{
cou++;
// Even if you'll fix mistakes above, your loop will stop
// at the first iteration, because of this return.
// You must put it right after the loop.
return cou;
}
// Your function actually returns nothing, because no iterations
// of the loop above is performed - so no return statement reached
// at all - it is undefined behaviour :(
// Put return here out of the loop;
}
I am trying to implement the algorithm RLE with simple input like:
ddddddddddhhhhhhhhhhhhhhhttttttttttttt
code:
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int main() {
vector<char> read;
ifstream file;
file.open("file.txt");
if (!file) {
cout << "Unable to open";
}
char v;
while(file>>v) {
read.push_back(v);
}
char x;
int count=0;
for(int i=0; i<read.size(); i++) {
x = read[i];
if(x != read[++i]) {
cout << x << "1";
}
while(x == read[++i]) {
count++;
}
cout << x << count;
count = 0;
}
return 0;
}
The output I am getting is:
d9d1h12h1t10t1
Please help me with the code.
Update: I have updated the question as I have realized few things.
Plus: This code produced no output, is there anything wrong which I am doing wrong?
char o;
char n;
int count=0;
for(int i=0; i<read.size(); i++) {
o = read[i];
n = read[++i];
while(o == n) {
count++;
}
cout << o << count;
if(o != n) {
cout << o << "1";
} count = 0;
}
return 0;
This loop:
char x;
int count=0;
for(int i=0; i<read.size(); i++) {
int j=i;
x = read[i];
if(x != read[++j]) {
cout << x << "1";
}
while(x == read[++j]) {
count++;
}
cout << x << count;
}
Has several errors. First, you should use two indices, i and j. i is going through each element of read, but then j is iterating through a subsequence too. What you want is to go through each element only once, and in each case either print or increase the count. However having a for loop and moving the index inside too is not a very good practice, is rather error-prone. Also you have to cout statements that are do not run at the right time (you don't wan to print something on every iteration, only when the character changes). You could do it with a while loop, or using a simpler structure like:
// If there are no characters finish
if (read.empty()) {
return 0;
}
// Get the first character
char lastChar = read[0];
int count = 1; // We have counted one character for now
// Go through each character (note start from 1 instead of 0)
for(int i = 1; i < read.size(); i++) {
// Get the next char
char newChar = read[i];
// If it is different, print the current count and reset the counter
if (lastChar != newChar) {
cout << lastChar << count;
count = 1;
lastChar = newChar;
} else { // Else increase the counter
count++;
}
}
// Print the last one
cout << lastChar << count;
return 0;
I'm trying to write a simple program which takes an array of chars, and spits it out backwards. I know there are plenty of other ways to shorten this using a library header function, but I wanted to do it using for loops just to get used to them.
#include<stdio.h>
#include<iostream>
using namespace std;
char string1[10];
int count = 0;
char stringy[10];
void enterString()
{
cout << "please enter a string: " << endl;
cin >> string1;
}
void stringCounter(const char stringLength[])
{
//initiate for loop i = 0
//if stringLength[i] does not does not equal 'i' then carry on
//increment i
for (int i = 0; stringLength[i] != '\0'; i++)
{
count++;
}
cout << "size of string is: " << count << endl;
}
void reverseString(int arraySize, char string2[])
{
int counter = 0;
for (int i = arraySize; i >= 0; string2[i--])
{
stringy[counter] = string2[i];
counter++;
}
stringy[count] = '\0';
cout << stringy << endl;
}
int main()
{
enterString();
stringCounter(string1);
reverseString(count, string1);
return 0;
}
This is the whole program. The program is failing in function reverseString. I can't work out how to successfully read the last index of the char array string2[] and copy it into the first index of char array stringy.
One, If the user enters a string more than 10 characters long then your enterString() function will access the array out of its bound, at cin>>string1. So better to use getline to make sure you don't read more than what your array can hold.
Two, with your current implementation the reverseString() function will write to the first element of the array with the null terminator character,if the arraySize<=10, and trying to display that string will not show you anything.
This:
cin >> string1;//will try to access the array out of its bound if user give more than it can hold,i.e 10 characters
...
for (int i = arraySize; i >= 0; string2[i--])
{
stringy[counter] = string2[i];//the first iteration will put the '\0' character as the first elements of stringy
counter++;
}
Should be changed to:
cin.getline(string1,10);//make sure to get not more than 10 characters,including the null terminator
.....
for (int i = arraySize-1; i >= 0; i--)
{
stringy[counter] = string2[i];
counter++;
}
There are many mistakes in your program. If this is the exact code you are compiling then it should throw many errors.
Following might help.
#include<iostream>
using namespace std;
void reverseString(int , char *);
int stringCounter(const char );
int stringCounter(const char stringLength[])
{
int count = 0;
for (int i = 0; stringLength[i] != '\0'; i++)
count++;
cout << "size of string is: " << count << endl;
return count;
}
void reverseString(int arraySize, char string2[])
{
int counter = 0;
char stringy[100];
for (int i = arraySize - 1; i >= 0; i--)
{
stringy[counter] = string2[i];
counter++;
}
stringy[counter] = '\0';
cout << stringy << endl;
}
int main()
{
char str[] = "string";
reverseString(stringCounter(str),str);
return 0;
}
I have a task that is difficult for me to handle. The task is: Create recursive function that can be generate a string of length N (N <= 100), formed by the letters 'A', 'B' and 'C' and does not containing two identical adjacent substring. For example: enter for N = 6 and the program should generate such a string in which no one else to repeated substrings: ABACAB. Wrong strings are: AABACA - because 'A' is to 'A'; ABCBCA - as 'BC' is to 'BC' and ABCABC is also wrong because 'ABC' is to 'ABC'.
I made a version of the program but an iterative way, here is the code:
#include <iostream>
#include <ctime>
using namespace std;
const char letters[] = "ABC";
char generate_rand()
{
return letters[rand() % 3];
}
int check(char *s, int pos)
{
for (int i = 1; i <= (pos + 1)/2; i++)
{
int flag = 1;
for (int j = 0; j < i; j++)
if (s[pos-j] != s[pos-i-j])
{
flag = 0;
break;
}
if (flag)
return 1;
}
return 0;
}
int main()
{
char s[100];
int n;
cout << "enter n: ";
cin >> n;
srand(time(NULL));
for (int i = 0; i < n; i++)
{
do
{
s[i] = generate_rand();
} while (check(s, i));
cout << s[i] << " ";
}
cout << " ok" << endl;
system("pause");
return 0;
}
I think the entrance of the recursive function may need to be the number of characters in the string, which will seek to repeat with an adjacent string and each time increased by 1, but not more than half the length of the original string, but do not know how to do it.
So lets start with a simple recursive function which prints 10 letters but doesn't check anything:
void addLetter(char* buf, int max_length)
{
int len = strlen(buf);
buf[len] = generate_rand();
if (strlen(buf) < max_length)
addLetter(buf);
}
int main()
{
srand(time(NULL)); //I forgot srand!
int max_length = 10; //ask user to input max_length, like you had earlier
char buf[100];
memset(buf,0,sizeof(buf));
addLetter(buf, max_length);
printf("\n%s\n", buf);
return 0;
}
Now lets change the recursive function, get it to check just 1 letter:
void addLetter(char* buf, int max_length)
{
int len = strlen(buf);
buf[len] = generate_rand();
if (len > 0)
{
if (buf[len] == buf[len-1])
buf[len] = 0;
}
if (strlen(buf) < max_length)
addLetter(buf);
}
Next step, check 2 letters with previous ones etc. You should be able to take it from here.