c-strings prog 7

Hello I am technically done with this project but I would like to get some feedback by someone more advanced.

It does not compile right now because I ran out of time but I would appreciate if someone can look at it so I can correct my mistakes later on.


*************************************************************************
here are some of the instructions if it helps to give you an idea of the project.

Purpose
To work with C++ c-strings and get additional experience with array processing.

Specifications
Declare an array to store a sentence (up to 80 characters). Prompt operator to enter a sentence (store in the array). Utilize the following functions to perform analysis on the input sentence.

********************************************************************************
FindLength

Primary responsibility: Return the length of the sentence. (Display length in main). HOW: Pass the sentence array to the function. Use a loop counter as a subscript to access each character: Initialize to zero and increment to locate the NULL character (end of string terminator '\0'). Return the counter value for display.

********************************************************************************
ConvertCaps

Primary responsibility: Convert the sentence to all capitals. (Display from main). HOW: Pass the sentence array to the function. Set up a loop looking for the NULL. Within the loop, examine each character of the string. If it is lower case (between 'a' and 'z'), convert to upper case by a simple math operation (see ASCII table).

********************************************************************************
CountLetters

Primary responsibility: Determines the number of letters contained in the sentence. (Display the results from main). How: Pass the sentence array to the function. Set up a loop to look for the NULL character. Inside the loop, use a decision construct to examine each character and determine whether the character is with the range of ‘A-Z’.

********************************************************************************
CountVowels

Primary responsibility: Count the number of each vowel. # of A's, # of E's, etc. (Display the results from main). HOW: Pass the sentence array and 5 counters to the function. (Use referenece variables for the 5 counters because you can only return one thing via the return statement). Set up a loop to look for the NULL character. Inside the loop, use a decision construct to examine each character and determine which vowel counter (if any) should be incremented.

CountWords Primary responsibility: Count the number of words in the sentence. (Display the results from main). HOW: Pass the sentence array to the function. Set up a loop looking for the NULL. Within the loop, examine each character of the string. Inside the loop, use a decision construct to examine each character and determine whether the character is a separator between words. Return the word count for display in main.

********************************************************************************
ReverseString

Primary responsibility: Copy the sentence in reverse order. (Display original sentence and reversed sentence from main). HOW: Pass the sentence array, an empty array, and the result from your FindLength function into this function. Initialize your loop counter to (string length - 1) and count down to zero. Use the loop counter as a subscript to access each character of the sentence from last to first. Assign that character to the empty array from first to last. (Note that you will need a second subscript for the second array.)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
 //Project Name: C-strings Prog 7
#include<iostream>
#include<cstring>
using namespace std;

void reverseWords(string s)


int main(){

int vowelCount(char *sptr)


// count number of letters

char str[] = "what what what!!!!!!!!!!";

cout << "sentence length = " << strlen(str);	
	
	// convert to uppercase
	for (int i = 0; i < strlen("level"); i++) {
	 	
	
    ch = toupper("level"[i]);
	cout  << ch;
  }	
  
	for (const auto& s : strs)
	cout << "How many letters are in " << s << "? " << strlen(s) << '\n';
	
	for (auto& s : strs){
		for (auto ch {s}; *ch; ++ch)
		*ch = static_cast<char>(toupper
		(static_cast<unsigned char>(*ch)));
		
		cout << s <<  " is "  << (!isPalindrome(s) ? "not " : "" ) << "a palindrome\n";
	}
	
	

	
	//count number of words 
	
	unsigned countWords(char *str)
{
    int state = OUT;
    unsigned wc = 0; // word count
 
    // Scan all characters one by one
    while (*str)
     {
        // If next character is a separator, set the
        // state as OUT
        if (*str == ' ' || *str == '\n' || *str == '\t')
            state = OUT;
 
        // If next character is not a word separator and
        // state is OUT, then set the state as IN and
        // increment word count
        else if (state == OUT)
        {
            state = IN;
            ++wc;
        }
 
        // Move to next character
        ++str;
         }
 
    return wc;
}	
	
	
	//conut number of vowels
	
	int vowelCount(char *sptr)
	{
		int cont = 0;
		
		while ((*sptr) != '\0'){
		
			if (*sptr =='a' || *sptr =='e' || *sptr =='i' 
			|| *sptr =='o' || *sptr =='u')  {
				
				count++;
			}
			sptr++;
		}
		
		return count;
	}
	
	return 0;
}

	
void reverseWords(string s)
{
	
	// temporary vector to store all words
	vector<string> tmp;
	string str = "";
	for (int i = 0; i < s.length(); i++)
	{
		
		// Check if we encounter space
		// push word(str) to vector
		// and make str NULL
		if (s[i] == ' ')
		{
			tmp.push_back(str);
			str = "";
		}

		// Else add character to
		// str to form current word
		else
			str += s[i];
	}

	// Last word remaining,add it to vector
	tmp.push_back(str);

	// Now print from last to first in vector
	int i;
	for (i = tmp.size() - 1; i > 0; i--)
		cout << tmp[i] << " ";
	// Last word remaining,print it
	cout << tmp[0] << endl;
}	
	
	

function protos need a ; line 6
and they do not belong inside main, line 11, they belong outside of functions. anywhere is legal but above main or in a .h file is more typical.

line 24 has many issues, from ch not existing to trying to address off a literal.

28, again, no such variable.

basically, you have a fairly solid grasp of what you want to do, but a very poor understanding of the C++ syntax and rules for legal code. The rest of the program follows that theme -- lots of not quite right syntax, but generally I see what you wanted to do. Stuff like using string and vector without including the headers...

one other thing, when writing code, you write a little (eg, a function to uppercase a string) and test that, get it working, then add something else. Don't write reams of stuff that you have to fix all together, but a little that you can fix and get working before adding more.

vowelcount can be done much simpler, and this is something everyone should see as the idea comes around over and over esp when trying to speed code up..

int counts[256]; //256 for all the ascii values including extended ascii.
for(all the letters in the string)
counts[letter]++
and after that
cout counts['a'], counts['e'] and so on for each vowel. if all same case, use that, but if you don't have same case, add ['a'] and ['A'] works too for each vowel use both versions and add them..

A more general comment is that this is a partial collection of various functions/code to implement some of the project specifications - but the implementation doesn't follow the HOW requirements and is not a coherent whole...


As an example of some of the required functions for c-style string arrays, consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>

size_t FindLength(const char* str) {
	const char* s {str};

	for (; *s; ++s);
	return s - str;
}

void ConvertCaps(char* str) {
	for (; *str; ++str)
		if (*str >= 'a' && *str <= 'z')
			*str -= 'a' - 'A';
}

size_t CountLetters(const char* str) {
	size_t cnt {};

	for (; *str; ++str)
		cnt += *str >= 'A' && *str <= 'Z';

	return cnt;
}

size_t CountWords(const char* str) {
	bool word {};
	size_t wc {};

	for (; *str; ++str)
		if (*str == ' ' || *str == '\n' || *str == '\t')
			word = false;
		else if (!word) {
			word = true;
			++wc;
		}

	return wc;
}

int main() {
	char text[] {"This is a test sentence"};

	std::cout << "Original string: " << text << '\n';
	std::cout << "Size: " << FindLength(text) << '\n';

	ConvertCaps(text);

	std::cout << "As caps: " << text << '\n';
	std::cout << "Number of letters: " << CountLetters(text) << '\n';
	std::cout << "Number of words: " << CountWords(text) << '\n';
}



Original string: This is a test sentence
Size: 23
As caps: THIS IS A TEST SENTENCE
Number of letters: 19
Number of words: 5

All I ever needed for C strings were compare (strcmp), length (strlen), substring (strstr), and sprintf/atoi/atof. There are a bunch more of them, but largely redundant to those.
With 20's format, I think the only thing cstrings can do now that c++ gets weird/won't like is destructive parsing, where you destroy the string as you go, eg injecting 0's over all the spaces to tokenize it.
An advantage of c-style strings is that for those that don't change they can be specified as constexpr rather than just const for std::string.

IMO std::string and std::vector/array should be taught first and only then c-style arrays/strings introduced as a 'just for your info' like topic.
Topic archived. No new replies allowed.