How to put together a string | Bytes (2024)

Alex T

How to put together a string | Bytes (1) 29 New Member

This is a snippet of my code that does not work:

Expand|Select|Wrap|Line Numbers

  1. while(ascii!=32)//whilecharacterisnotspace
  2. {
  3. letter=(char)infile.get();//retreivenextcharacter
  4. ascii=(int)letter;
  5. if(ascii==32)
  6. break;
  7. word=word+letter;
  8. }

I use a text file with 3 words "this this this". The string word records the letters that are found but when it gets to the spacebar, with ascii code 32, instead prints -1 and the "y with dots over it symbol" goes into the string.

How should I fix this?

Oct 7 '10 #1

Subscribe Reply

7 How to put together a string | Bytes (2) 2598 How to put together a string | Bytes (3)

ash*tpro

542 How to put together a string | Bytes (5) Recognized Expert Contributor

Try printing letter after line 3 and ascii after line 4
Send the results.

Oct 8 '10 #2

reply

donbock

2,426 How to put together a string | Bytes (6) Recognized Expert Top Contributor

What is word? Is it a string where the plus sign is overloaded to mean concatenate or is it an integral type? If it is an integral type then computing the sum of several characters is not going to be meaningful.

What is the initial value of ascii? That is, why do you expect to be able to get into the while loop?

By the way, replace the magic number "32" with character constant ' '.

Oct 8 '10 #3

reply

Alex T

29 How to put together a string | Bytes (7) New Member

Here is the complete code for your convenience:

Expand|Select|Wrap|Line Numbers

  1. #include<algorithm>
  2. #include<fstream>
  3. #include<iomanip>
  4. #include<iostream>
  5. #include<map>
  6. #include<string>
  7. //NEEDSTOBEFIXED:FINDSLETTERSNOTWORDS
  8. usingnamespacestd;
  9. typedefmap<string,unsignedint>map_string_int;
  10. typedefmultimap<unsignedint,string>mmap_int_string;
  11. intmain()//intargc,char*argv[]insertintomainfortest
  12. {
  13. charletter;
  14. intcounter=0,number,value;
  15. shortascii=0;
  16. stringword,filename;
  17. mmap_int_string::const_iteratoriElementFound;
  18. map_string_intstring_to_int;
  19. mmap_int_stringint_to_string;
  20. ifstreaminfile;
  21. cout<<"Enternameoffile:";
  22. getline(cin,filename);
  23. infile.open(filename);//argv[1]insertfortest
  24. cout<<endl;
  25. cout<<"letter|ascii|word"<<endl;
  26. while(infile.good())
  27. {
  28. while(!infile.eof())
  29. {
  30. while(ascii!=-1)//whilecharacterisnotspace
  31. {
  32. letter=(char)infile.get();//retreivenextcharacter
  33. cout<<letter<<"|";
  34. ascii=(int)letter;
  35. cout<<ascii<<"|";
  36. if(ascii==-1)
  37. break;
  38. word=word+letter;
  39. cout<<word<<endl;
  40. }
  41. //trytofindwordinindexmap
  42. map_string_int::const_iteratorindexElementFound=string_to_int.find(word);
  43. if(indexElementFound!=string_to_int.end())
  44. {
  45. //iffound,createanotherpairinmultimap
  46. value=indexElementFound->second;
  47. int_to_string.insert(make_pair(value,word));
  48. }else{
  49. //ifnotfound,createpairinbothindexmapandmultimap
  50. counter++;
  51. string_to_int.insert(make_pair(word,counter));
  52. int_to_string.insert(make_pair(counter,word));
  53. }
  54. word="";//clearwordfornextpartoffile
  55. }
  56. //createalistbysearchingmultimap
  57. for(value=0;value<counter;value++)
  58. {
  59. number=int_to_string.count(value);
  60. iElementFound=int_to_string.find(value);
  61. cout<<iElementFound->second<<":"<<number<<endl;
  62. }
  63. }
  64. infile.close();
  65. charresponse;
  66. cin>>response;
  67. return0;
  68. }

My goal for this is to find the frequency of each word in the text file.

The text file has only the word "this".

For convenience, I have altered the code to make the output more meaningful: here it is.

Enter name of file: C:\\test1.txt

letter | ascii | word
t | 116 | t
h | 104 | th
i | 105 | thi
s | 115 | this
| -1 |

This is as far as it gets before the program stops functioning. Please assist.

Oct 8 '10 #4

ash*tpro

542 How to put together a string | Bytes (9) Recognized Expert Contributor

ascii value -1 represents end of file and not space.
space has ascii value 32.

There are lots of logical problems in this code.
I have fixed the few of them. see if this code runs at your end. This is g++ compliant, you may need to make few changes.

Expand|Select|Wrap|Line Numbers

  1. #include<algorithm>
  2. #include<fstream>
  3. #include<iomanip>
  4. #include<iostream>
  5. #include<map>
  6. #include<string>
  7. //NEEDSTOBEFIXED:FINDSLETTERSNOTWORDS
  8. usingnamespacestd;
  9. typedefmap<string,unsignedint>map_string_int;
  10. typedefmultimap<unsignedint,string>mmap_int_string;
  11. intmain()//intargc,char*argv[]insertintomainfortest
  12. {
  13. charletter;
  14. intcounter=0,number,value;
  15. shortascii=0;
  16. stringword,filename;
  17. mmap_int_string::const_iteratoriElementFound;
  18. map_string_intstring_to_int;
  19. mmap_int_stringint_to_string;
  20. ifstreaminfile;
  21. cout<<"Enternameoffile:";
  22. getline(cin,filename);
  23. cout<<filename;
  24. //exit(0);
  25. infile.open(filename.c_str(),ifstream::in);//argv[1]insertfortest
  26. cout<<endl;
  27. cout<<"letter|ascii|word"<<endl;
  28. intout=0;
  29. while(infile.good()&&out==0)
  30. {
  31. while(!infile.eof()&&out==0)
  32. {
  33. while(1)
  34. {
  35. letter=(char)infile.get();//retreivenextcharacter
  36. cout<<letter<<"|";
  37. ascii=(int)letter;
  38. cout<<ascii<<"|";
  39. if(ascii==32||ascii==10)
  40. {
  41. break;
  42. }
  43. if(infile.eof())
  44. {
  45. out=1;
  46. break;
  47. }
  48. word=word+letter;
  49. cout<<word<<endl;
  50. }
  51. //trytofindwordinindexmap
  52. map_string_int::const_iteratorindexElementFound=string_to_int.find(word);
  53. if(indexElementFound!=string_to_int.end())
  54. {
  55. //iffound,createanotherpairinmultimap
  56. value=indexElementFound->second;
  57. int_to_string.insert(make_pair(value,word));
  58. }else{
  59. //ifnotfound,createpairinbothindexmapandmultimap
  60. counter++;
  61. string_to_int.insert(make_pair(word,counter));
  62. int_to_string.insert(make_pair(counter,word));
  63. }
  64. word="";//clearwordfornextpartoffile
  65. }
  66. //createalistbysearchingmultimap
  67. for(value=0;value<counter;value++)
  68. {
  69. number=int_to_string.count(value);
  70. iElementFound=int_to_string.find(value);
  71. if(iElementFound!=int_to_string.end())
  72. {
  73. cout<<endl<<int_to_string.find(value)->second<<":"<<number<<endl;
  74. }
  75. }
  76. }
  77. infile.close();
  78. charresponse;
  79. cin>>response;
  80. return0;
  81. }

Oct 9 '10 #5

reply

donbock

2,426 How to put together a string | Bytes (10) Recognized Expert Top Contributor

Please change line 48 from

Expand|Select|Wrap|Line Numbers

  1. if(ascii==32||ascii==10)

to

Expand|Select|Wrap|Line Numbers

  1. if((ascii=='')||(ascii=='\n'))

Even better would be

Expand|Select|Wrap|Line Numbers

  1. if(isspace(ascii))

Lines 45 and 47 print the character before you check to see if it is a space. Thus, a single trailing space gets printed with each word. Is that what you wanted to do?

Don't you want to discard leading spaces too? Consider a state machine with two states: in-a-word and between-words. The initial state is between-words. Any non-whitespace character causes a transition from between-words to in-a-word. Any whitespace character causes a transition from in-a-word to between-words.

Oct 9 '10 #6

reply

Alex T

29 How to put together a string | Bytes (11) New Member

Can you clarify what exactly changed in my code?

Oct 9 '10 #7

reply

Alex T

29 How to put together a string | Bytes (12) New Member

Nevermind, don't. I fixed the problem. Thank you all for your help.

Oct 9 '10 #8

reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 31178

Want to split string on 1 or more white spaces

by: Stu Cazzo |last post by:

I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it will split myString up using the delimiter of 1 space so that

Java

8 2793

String vs new String

by: Grant Wagner |last post by:

I'm a bit confused by String() (typeof 'string') vs new String() (typeof 'object'). When you need to access a method or property of a -String-, what type is JavaScript expecting (or rather, what should you provide), a -String object- or a -string-? Given the following benchmark: var t = (new Date()).getTime(); for (var ii = 0; ii < 100000; ++ii) { var x = (String('hi')).charAt(0); // typeof 'string'

Javascript

7 12695

String enumeration/grouping

by: archway |last post by:

I know you cannot have string enumerations such as: enum myStringEnum { enumItem1 = "value 1", enumItem2 = "value 2", etc } However, I was wondering whether you had ever created something that would mimic this? I have tried the following:

C# / C Sharp

1 953

StringBuilder AppendFormart cannot handle String!!

by: Jay Balapa |last post by:

Hello, If I use AppendFormat with string as a parameter. I get string cannot be converted to IFormatProvider. This occurs in 2.0 Thanks. Jay

ASP.NET

1 29785

PHP Fatal error: Cannot use string offset as an array

by: Jim Michaels |last post by:

=> Array ( => UML:CLASS => open => 5 => Array ( => .:00000000000008EC => quiz_batteries => public

PHP

6 4114

Help with "cannot assign string" error

by: Don Lancaster |last post by:

I need to progrmatically do this inside a loop this.fh03.value = fixFloat (Harms, numPoints) ; with the numbers changing per an index. If I try curHvals = "03" ; // (derived from index to provide leading zero)

Javascript

7 2935

Cannot post string "union select" php form

by: php_mysql_beginer911 |last post by:

Hi .. hope someone will help i am trying to figure it out why i cannot post string "union select" every time i try to post data which content union and select .. the page doesn't get posted and it shows error page not found on this server i googled and found some people use union and select to hack sites (mysql injection) i guess the server i am using has some kind of filter and if a post string content "union select" ... it simply...

PHP

5 4612

Cannot use string offset as an array

by: samatair |last post by:

I get an error message like this. Fatal error: Cannot use string offset as an array in D:\www\site\includes\change_preference.inc.php on line 310 $cityName = $row2; The above code is causing this error. Please let me know what is wrong with this code. How can I rectify this error. Here $i, $j consists of integer value. which are used to perform a for loop specific number of times. while $row2 brings data from a database.

PHP

1 1996

Cannot get string input to work

by: andrewc |last post by:

I am trying to get a 2 character string into my program in order to then determine a command based on the string. This is in an embedded application. Right at the top of my program I have declared static char comin; // declared as 'static' - I will use it in a number of places . . . void main ()

C / C++

19 12829

Cannot Convert string to class type

by: Queen Soso |last post by:

hi there, When I run this line I get an error: obj.number_type = dropdownlist1.selectedItem.value; number_type is a class type and I want to put a string value in it from a drop down list. this is the error:

C# / C Sharp

9591

What is ONU?

by: marktang |last post by:

ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...

General

10057

Maximizing Business Potential: The Nexus of Website Design and Digital Marketing

by: jinu1996 |last post by:

In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...

Online Marketing

1 10002

The easy way to turn off automatic updates for Windows 10/11

by: Hystou |last post by:

Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...

Windows Server

9869

Discussion: How does Zigbee compare with other wireless protocols in smart home applications?

by: tracyyun |last post by:

Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...

General

8883

AI Job Threat for Devs

by: agi2029 |last post by:

Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...

Career Advice

1 7415

Access Europe - Using VBA to create a class based on a table - Wed 1 May

by: isladogs |last post by:

The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...

Microsoft Access / VBA

5449

Windows Forms - .Net 8.0

by: adsilva |last post by:

A Windows Forms form does not have the event Unload, like VB6. What one acts like?

Visual Basic .NET

2 3575

How to add payments to a PHP MySQL app.

by: muto222 |last post by:

How can i add a mobile payment intergratation into php mysql website.

PHP

3 2816

Comprehensive Guide to Website Development in Toronto: Expert Insights from BSMN Consultancy

by: bsmnconsultancy |last post by:

In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

General

How to put together a string | Bytes (2024)
Top Articles
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 6489

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.