【发布时间】:2018-05-07 21:10:06
【问题描述】:
我正在设计一个使用“dir > music.txt”获取目录列表的程序。我的目标是从文件中删除权限和日期,并按字母顺序排列艺术家列表。使用“getline(file, input)”时,将“input”变量发送到屏幕时,每个字符之间会出现空格。代码如下:
#include "stdafx.h"
using namespace std;
void AlphaSort(string (&data)[300], int size);
void PrintArray(string(&data)[300]);
// This program will read in an array, the program will then remove any text
// that is before 59 characters, then the program will remove any spaces that
// are not succeeded by letters.
int main()
{
fstream file;
string input;
string data[300];
file.open("music.txt");
while (getline(file, input))
{
cout << input << endl;
// Scroll through the entire file. Copy the lines into memory
for (int i = 0; i <= input.length() - 1; i++)
{
// Process input here...
}
}
// The array has been loaded into memory, run the sort
//AlphaSort(data, 300);
//PrintArray(data);
return 0;
}
以下是输出示例:
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 5 A M E i f f e l 6 5
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 9 A M O n e R e p u b l i c
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 8 A M M a r o o n 5
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 8 A M L u m i n e e r s
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 8 A M M y C h e m i c a l R o m a n c e
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 4 A M B o b M a r l e y
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 9 A M P a r a m o r e
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 7 A M I n c u b u s
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 4 A M C a r p e n t e r s
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 5 A M F a i t h N o M o r e
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 2 A M B a s t i l l e
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 6 A M F r a n k i e G o e s T o H o l l y w o o d
d - - - - - 8 / 7 / 2 0 1 7 1 1 : 1 7 A M H o o b a s t a n k
如您所见,每个字符之间都有空格。过去一个小时我一直在看这个。我有更“正确”的方式从文件输入吗?下面是每个字符之间不包含空格的输入文件:
d----- 8/7/2017 11:15 AM Eiffel 65
d----- 8/7/2017 11:19 AM One Republic
d----- 8/7/2017 11:18 AM Maroon 5
d----- 8/7/2017 11:18 AM Lumineers
d----- 8/7/2017 11:18 AM My Chemical Romance
d----- 8/7/2017 11:14 AM Bob Marley
d----- 8/7/2017 11:19 AM Paramore
d----- 8/7/2017 11:17 AM Incubus
d----- 8/7/2017 11:14 AM Carpenters
d----- 8/7/2017 11:15 AM Faith No More
d----- 8/7/2017 11:12 AM Bastille
d----- 8/7/2017 11:16 AM Frankie Goes To Hollywood
d----- 8/7/2017 11:17 AM Hoobastank
d----- 8/7/2017 11:21 AM Young The Giant
d----- 8/7/2017 11:15 AM Disturbed
d----- 8/7/2017 11:12 AM Authority Zero
【问题讨论】:
-
这是
cout << input << endl;的输出? -
不相关的潜在错误:
i <= input.length();允许您越过字符串末尾。 -
输入可以是非ASCII编码吗?
-
用二进制编辑器查看文件。可能是用了多字节编码,C++看不懂。
-
为什么不直接读取目录而不是解析'dir'的结果