Print concepts that have spaces in them

I have an assignment to read from a file and to print only the names that have spaces in them. This is my text file:
Arkansas
California
Colorado
Connecticut
Delaware
District Of Columbia
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming
American Samoa
District of Columbia
Guam
Northern Mariana Islands
Puerto Rico
United States Virgin Islands

How do I get specific names to print? Thank you for your time.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <fstream>

bool has_char( const std::string& str, char ch )
{
    // http://www.cplusplus.com/reference/string/string/find/
    return str.find(ch) != std::string::npos ;
}

bool has_space( const std::string& str ) { return has_char( str, ' ' ) ; }

int main()
{
    std::ifstream file( "whatever.txt" ) ; // open file for input

    std::string line ;
    // http://www.cplusplus.com/reference/string/string/getline/
    while( std::getline( file, line ) ) // for each line in the file
        if( has_space(line) ) std::cout << line << '\n' ; // print it if it has a space
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>

int main()
{
    std::string a = "Arkansas";
    std::string b = "District of Columbia";
    std::string c = "Nevada";
    std::string d = "American Samoa";
    std::vector<std::string> stringVec {a, b, c, d};

    for (auto& elem : stringVec)
    {
        size_t foundSpace = elem.find_first_of(" ");
        if(foundSpace != std::string::npos)
        {
            std::cout << elem << '\n';
        }
    }
}

Output
1
2
District of Columbia
American Samoa
Including the file-read:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>

int main()
{
    std::ifstream inFile("D:\\states.txt");
    std::string line;
    while (getline(inFile, line))
    {
        size_t foundSpace = line.find_first_of(" ");
        if(foundSpace != std::string::npos)
        {
            std::cout << line << '\n';
        }
    }
}

Last edited on
Thank you both so much! These worked perfectly I really appreciate the help.
Topic archived. No new replies allowed.